Wednesday, January 4, 2012

Clear or Reset All Controls using JavaScript in Asp.Net


In Design
<asp:Button ID="Clear Form" runat="server" OnClientClick="ClearAllControls(); return False" />

JavaScript
function ClearAllControls() {
           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.selectedIndex = 0;
                       break;
                   case "select-multiple":
                       doc.selectedIndex = 0;
                       break;
                   default:
                       break;
               }
           }       
       }

Here I have used “OnClientClick="ClearAllControls(); return False” because I don’t want to do the Postback to this button. If you want to do the postback to this button then remove return False.

I hope this article will be very helpful to all. Thanks for reading this article.

“Keep reading and share the knowledge”  
“Grow more trees to save the Earth”

No comments:

Post a Comment