Introduction
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.
Background
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.
Using the code
- 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 :
<script type="text/javascript">
function resetFields(form) {
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); if (type == 'text' || type == 'password' || tag == 'textarea' || type=='file')
this.value = "";
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = 0;
});
}
</script>
- And then simply call this function on button
OnClientClick
event.
<asp:Button ID="Button1" runat="server" Text="Reset" OnClientClick="resetFields(form1);" />
- Press f5 and check.