[thelist] Proper way to access elements in a fieldset via DOM?

Edwin Martin edwin at bitstorm.org
Fri Jun 18 03:51:53 CDT 2004


Gee Starr wrote:

> Right, so I've been away from JavaScript for three or four years and I
> seem to be a bit stiff in the joints.
> 
> ### The task:
> 
> Use a simple bit of JS to check all text inputs in a form with a similar
> name and display the sum of said fields in another text input.

This works (for 95% of all browsers):

function wksheetTotal() {
   var total = 0;
   fields = document.worksheet.getElementsByTagName( "input" );
   for (var i = 0; i < fields.length; i++)
   {
     if (fields[i].name.indexOf('field') > -1)
     {
         thisnum = parseFloat(fields[i].value);
         total += thisnum;
     }
   }
   document.worksheet.total.value = total;
}

Edwin Martin


> 
> 
> ### The JavaScript function:
> 
> <script language="JavaScript">
> <!--
> function wksheetTotal() {
>   var total = 0;
>   for (var i = 0; i < document.worksheet.elements.length; i++)
>   {
>     if (document.worksheet.elements[i].name.indexOf('field') > -1)
>     {
>         thisnum = parseFloat(document.worksheet.elements[i].value);
>         total += thisnum;
>     }
>   }
>   document.worksheet.total.value = total;
> }
> 
> //-->
> </script>
> 
> 
> ### The form (simplified):
> 
> <form name="worksheet" metod="post" action="">
>   <fieldset>
>     <legend>The Sample Fields</legend>
> 
>       <p>Field one:
>       <input name="field[]" type="text" onChange="wksheetTotal()"
> onKeyUp="wksheetTotal()" value="0" size="3" maxlength="3" />
>       </p>
> 
>       <p>Field two:
>       <input name="field[]" type="text" onChange="wksheetTotal()"
> onKeyUp="wksheetTotal()" value="0" size="3"  />
>       </p>
> 
>       <p>Total:
>       <input name="total" type="text" value="0" size="6" />
>       </p>
> 
>     </fieldset>
> </form>
> 
> 
> Surprisingly (to me), the above scenario will not work. However, it works
> as expected if you remove the fieldset tag from the form. As you can
> expect, the fieldset needs to stay.
> 
> I assume I am tripping over the DOM, but my first half-dozen alternative
> approaches have produced no joy. I welcome the embarrassment of having the
> simple solution pointed out to me.
> 
> Example in action (and of inaction) are available at:
> 
> <http://www.geedev.com/demo/demo-fieldset.htm>
> 
> 



More information about the thelist mailing list