Introduction
This is a very common requirement that always comes across while building a form. Suppose we have lots of controls such as text box, drop down list, radio button, check box, and file uploader control. If you want to reset them on single click, what will be your approach? Obviously the choice is to clear each field from JavaScript function or you can do this server side as well.
Background
Here I am sharing an important JavaScript function, which can bring them back in the original state. You just need to call the junction in the client click. The most important thing about this function is that it can reset the fileuploader control as well.
Salient features:
- Using this code, you can reset HTML controls as well as ASP controls like text box, text area, radio buttons, etc.
- This function can reset the File Upload control as well.
- Using this, we can reset .NET Validation Controls too, like
RequiredFieldValidater
, etc.
- This code has no issue with any browser like FireFox, Internet Explorer, Google Chrome, Safari, etc…
Using the Code
Just copy the JavaScript function on your page and then simply call the JS function on button onclick event and function reset all types of controls on your page.
And for reset validation controls, you just set your validator control prefix on variable 'validationControlsPrefix
'.
For more details, please refer to the uploaded code:
<script type="text/javascript">
function ClearAllControls()
{
var validationControlsPrefix = "req";
resetmsg(validationControlsPrefix);
for (i=0; i<document.forms[0].length; i++)
{
doc = document.forms[0].elements[i];
switch (doc.type)
{
case "text" :
doc.value = "";
break;
case "checkbox" :
doc.checked = false;
break;
case "radio" :
doc.checked = false;
break;
case "select-one" :
doc.options[doc.selectedIndex].selected = false;
doc.selectedIndex = 0;
break;
case "select-multiple" :
while (doc.selectedIndex != -1)
{
indx = doc.selectedIndex;
doc.options[indx].selected = false;
}
doc.selected = false;
break;
case "textarea":
doc.value = "";
break;
case "file" :
var browser=navigator.appName;
if(browser == 'Microsoft Internet Explorer')
{
var fil = doc;
n=fil.createTextRange();
n.execCommand('delete');
}
else
{
doc.value='';
}
break;
default :
break;
}
}
}
function resetmsg(validationControlsPrefix)
{
var spans;
var browser=navigator.appName;
if(browser == 'Microsoft Internet Explorer')
{
spans = document.all.tags('span');
}
else
{
spans = document.getElementsByTagName('span');
}
if (spans)
{
for (var i = 0; i < spans.length; i++)
{
var prefixLength = "" + validationControlsPrefix.length;
var currID = "" + spans[i].id
if ((currID != '') && (prefixLength != ''))
{
if (currID.substring(0,prefixLength) ==
validationControlsPrefix)
{
spans[i].style.display = "none";
}
}
}
}
}
</script>
History
- 9th November, 2009: Initial post