Clear form elements with jquery

Hello friends. Here is the code to clear form elements. You need to pass only the form ID in the function and thats all. The form would be cleared. Thanks !!

The Javascript

<script src="https://ajax.googleapis.com/ajax/libs/
jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function clear_form(form) {
       $('#'+form).find(':input').each(function() {
            switch(this.type) {
                case 'text':
                case 'password':
                case 'textarea':
                case 'select-one':
                case 'select-multiple':
                        $(this).val('');
                        break;
                case 'radio':
                case 'checkbox':
                        this.checked = false;
            }
        });
     }
</script>


Html form

<form id="myForm" name="myForm" method="post" action="">
  <table border="0" cellpadding="2" cellspacing="2">
    <tr>
      <td>Gender</td>
      <td><input name="sex" type="radio" value="m" />
        Male
        <input name="sex" type="radio" value="f" />
        Female</td>
    </tr>
    <tr>
      <td>I like</td>
      <td><input name="like" type="checkbox" value="cricket" />
        Cricket
        <input name="like" type="checkbox" value="football" />
        Football</td>
    </tr>
    <tr>
      <td>Name</td>
      <td><input name="name" type="text"  /></td>
    </tr>
    <tr>
      <td>Country</td>
      <td><select name="select" id="select"  >
          <option value="">Select Country</option>
          <option value="australia">Australia</option>
          <option value="canada">Canada</option>
          <option value="india">India</option>
          <option value="uk">Uk</option>
          <option value="usa">USA</option>
        </select></td>
    </tr>
    <tr>
      <td>Address</td>
      <td><textarea name="address"></textarea></td>
    </tr>
  </table>
</form>
<input type="button" value="Clear" onclick="clear_form('myForm')" />


The Example
 

Gender Male Female
I like Cricket Football
Name
Country
Address
Clear form elements with jquery Clear form elements with jquery Reviewed by JS Pixels on October 01, 2011 Rating: 5

No comments:

Altaf Web. Powered by Blogger.