This is a common requirement while developing a web form which consists of various Input controls like Textbox, Radio Button, Checkbox, DropdownList, File Upload etc. We also need to have a button which clears the value of all the fields. Generally we named this Button as Reset.
Every developers have their different approach of Resetting all the controls on a single click. I am explaining a simple jQuery function which is called on the click of button and reset values of all the controls used in the web page.
Take a reference of latest jQuery in your source. I am using jquery-1.10.2.js in my example.
In the form tag of your Web form add your controls which you would like to use in the page.
Simply Copy and Paste the below code in the script tag :
Collapse | Copy Code
<script type="text/javascript"> function resetFields(form) { $(':input', form).each(function() { var type = this.type; var tag = this.tagName.toLowerCase(); // normalize case // to reset the value attr of text inputs, // password inputs, fileUpload and textareas if (type == 'text' || type == 'password' || tag == 'textarea' || type=='file') this.value = ""; // checkboxes and radios need to have their checked state cleared else if (type == 'checkbox' || type == 'radio') this.checked = false; // select elements need to have their 'selectedIndex' property set to -1 // (this works for both single and multiple select elements) else if (tag == 'select') this.selectedIndex = 0; }); } </script>
And then simply call this function on button OnClientClick
event.
Collapse | Copy Code
<asp:Button ID="Button1" runat="server" Text="Reset" OnClientClick="resetFields(form1);" />
Press f5 and check.
转至:http://www.dfwlt.com/forum.php?mod=viewthread&tid=699&extra=