Clear All Controls Using a single Javascript function

  1. function ClearTextbox(ParentControl) {    
  2.     var control = $(ParentControl).get(0);    
  3.     var list = control.getElementsByTagName("input");    
  4.     var textAreaList = control.getElementsByTagName("textarea");    
  5.     var selectList = control.getElementsByTagName("select");    
  6.     for (var i = 0; i < list.length; i++) {    
  7.         var attr = list[i].getAttribute('type');    
  8.         var control = document.getElementById(list[i].id);    
  9.         switch (attr) {    
  10.             case "text":    
  11.                 $(control).val('');    
  12.                 break;    
  13.                     
  14.             case "hidden":    
  15.                 $(control).val('');    
  16.                 break;    
  17.     
  18.             case "checkbox":    
  19.                 control.checked = false;    
  20.                 break;    
  21.     
  22.             case "radio":    
  23.                 control.checked = false;    
  24.                 break;    
  25.     
  26.             case "range":    
  27.                 control.setAttribute('value''0');    
  28.                 break;    
  29.     
  30.             case "file":    
  31.                 control.setAttribute('value''');    
  32.                 break;    
  33.         }    
  34.     }    
  35.     
  36.     for (var i = 0; i < textAreaList.length; i++) {    
  37.         var control = document.getElementById(textAreaList[i].id);    
  38.         $(control).val('');    
  39.     }    
  40.     for (var i = 0; i < selectList.length; i++) {    
  41.         $(selectList[i]).val('');    
  42.     }    
  43. }   
Make a Call to the function.
  1. <script>    
  2.            $('#btnClear').click(function (e) {    
  3.                 e.preventDefault();    
  4.                 ClearTextbox('#form');//Pass the Parent control ID of Controls u want to clear    
  5. //Here I have Passes the ID of the forms tag clear all the controls in the form.  
  6. //In Case you want to clear only the contents in a Particular div or table, we can pass the ID of that div or //table and it will clear the elements only in that div or table.  
  7.                                          
  8.             });    
  9. </script>