Monday, August 30, 2010

Clearing ASP.Net FileUpload Control using jQuery

Here i am going to discuss about on how to clear the file upload control using jQuery. To clear file upload control, you have to place file upload control within the DIV tag like below.

HTML CODE:


<div id="div_fileupload">
<asp:FileUpload ID="fileUpload" runat="server" onkeypress="return false;" />
</div>


jQuery Custom Function:


// Clearing text of file upload control by means of replacing with HTML content.
// you can place this code in your JS file.
$.ClearFileUpload = function (fileUploadControlId) {
try {
document.getElementById(fileUploadControlId).innerHTML = document.getElementById(fileUploadControlId).innerHTML;
$(fileUploadControlId).focus();
} catch (e) {
//alert(e.Description);
}
}


Calling jQuery Custom Function from ASP.Net Design View:



function Checkfiles() {
var value = $('#fileUpload').val().toLowerCase();
if (value.length != 0) {
if (/.*\.(gif)|(jpeg)|(jpg)|(png)$/.test(value))
return true;

$.ClearFileUpload('div_fileupload');
alert('Please Upload Gif or Jpg Images, or Png Files Only.');
return false;
}
else {
return true;
}
}

You can call the above function in your ASP.Net Submit button OnClientClick event with checking the file extensions.