Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Reset all Fields using jQuery

0.00/5 (No votes)
19 May 2014 1  
Cleared all the fields in the asp.net form using jQuery on single click

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

  1. Take a reference of latest jQuery in your source. I am using jquery-1.10.2.js in my example.
  2. In the form tag of your Web form add your controls which you would like to use in the page.
  3. 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(); // 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> 
  1. And then simply call this function on button OnClientClick event.
<asp:Button ID="Button1" runat="server" Text="Reset" OnClientClick="resetFields(form1);" />  
  1. Press f5 and check.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here