how to access checkboxes and their values with getElementsByName

mendahu picture mendahu · Jan 5, 2011 · Viewed 38.6k times · Source

Suppose I have the following section of a form:

<td>
 <p>
  <input type="checkbox" name="faddon" onchange="iaddon()" value="89.00" /><br />
  <input type="checkbox" name="faddon" onchange="iaddon()" value="29.00" /><br />
  <input type="checkbox" name="faddon" onchange="iaddon()" value="49.00" /><br />
  <input type="checkbox" name="faddon" onchange="iaddon()" value="39.00" />
 </p>
</td>

<td>
 <p>
  <input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
  <input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
  <input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
  <input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" />
 </p>
</td>

Every time the user selects or deselects a checkbox, I need the script to recalculate the variable addon to the total of all values of the boxes which are checked. This is the code I came up with first, but it does not appear to work for me:

function iaddon() {
 addon=0;
 av=document.getElementsByName("faddon");
 for (e=0;e<av.length;e++) {
  if (av[e].checked==true) {
   addon+=av[e];
   }
  }
 }

The script keeps returning NaN as the value of addon. At first, I wondered if javascript was reading the values as strings and not integers, but adding a (x)*1 around av[e] did not fix this. Then, I read a little more into getElementsByName and read about it possibly not being a typical array, but instead a nodeList.

I'm new to Javascript and can't figure out after hours of googling how to manipulate this nodeList. Any help is appreciated. I'd like to keep the 8 checkboxes in seperate table cells, so using something like childNodes wouldn't exactly work here, as far as I can tell. I also would like to steer clear of any jQuery at this point...I'm still learning and I want to make sure I understand how to do it in plain old javascript first. Thanks!

Answer

Chandu picture Chandu · Jan 5, 2011

You need to use the value property and also parse it to a number. e.g:

function iaddon()
{
    addon = 0;
    for (e = 0; e < av.length; e++)
    {
        if (av[e].checked == true)
        {
            addon += parseInt(av[e].value, 10);
        }
    }
}