Weird Thoughts From Eric's Head

Tags - Categories : All | AJAX | BUSINESS | PERSONAL | PROGRAMMING | BOOK REVIEW

Resetting Forms with JavaScript
Well we all know that the reset button on a form resets the fields of a form back to what their states initially were set to. We can also cause the same effect by performing the following statement:

document.formName.reset();
Now that is fine and dandy if you want the forms to go back to orginal state, but what if you want everything wiped clean? Well you can loop through the form array and detect the type of the element. If it is a text based element, we reset the value. A checkbox/radio button selections get set to false. And a select element's selected Index is set to -1.
<script type="text/javascript">
  function ResetForm(xFormName){
    var arrElems = document.forms[xFormName].elements;
    document.forms[xFormName].reset();
    for(xi=0;xi<arrElems.length;xi++){
      if(arrElems[xi].type.toLowerCase() == "text" ||
         arrElems[xi].type.toLowerCase() == "hidden" ||
         arrElems[xi].type.toLowerCase() == "password" ||
         arrElems[xi].type.toLowerCase() == "textarea")
        arrElems[xi].value="";
      else if(arrElems[xi].type.toLowerCase() == "radio" ||
              arrElems[xi].type.toLowerCase() == "checkbox")
        arrElems[xi].selected = false;
      else if(arrElems[xi].type.toLowerCase().indexOf("select") != -1)
        arrElems[xi].selectedIndex = -1;
    }
  }
</script>
I probably could have used a switch statment to speed up the processing of the loop, but you would only notice the time difference if we were talking 1000's of elements. Sorry that the format is rather ugly, but I did not want to mess up everyone's RSS readers with long strings like normal!

Hope that helps!

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages