[Javascript] Reset the value of a SET of fields

Shawn Milo milo at linuxmail.org
Thu May 20 07:08:44 CDT 2004


David,

You have been given some good suggestions by others, but I
thought I'd take a crack at it. 

In my opinion, the easiest (least code) way to do it is with 
a simple function like this:

         function clearSet(setNo){
            var regex = setNo + '$';
            for (x=0;x<document.forms[0].elements.length;x++){
               if (document.forms[0].elements[x].id.match(regex)){
                  document.forms[0].elements[x].value = '';
               }
            }
         }


You can call the function like this:
         clearSet('03');


I tested this with this HTML:

      <form id="testForm" method="post" action="./action.php">

         <input type="text" id="name01" value="Fred" />
         <input type="text" id="phone01" value="555-1212" />
         <input type="text" id="city01" value="Quahog" />
         <br/>
         <input type="text" id="name02" value="Fred" />
         <input type="text" id="phone02" value="555-1212" />
         <input type="text" id="city02" value="Quahog" />
         <br/>
         <input type="text" id="name03" value="Fred" />
         <input type="text" id="phone03" value="555-1212" />
         <input type="text" id="city03" value="Quahog" />

      </form>


Notes:  You can/should replace the 'forms[0]' in my function
with:  forms['formName'], because my code assumes only one
form on the page.  There may be a reason why doing it this
way isn't the best way, but I like to use regular expressions
whenever possible.

Shawn



More information about the Javascript mailing list