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

Gee Starr geestarr at geedev.com
Thu Jun 17 18:37:16 CDT 2004


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.


### 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>


-- 
//. gee of geedev dot com


More information about the thelist mailing list