Friday, May 10, 2024
96
rated 0 times [  100] [ 4]  / answers: 1 / hits: 39964  / 14 Years ago, wed, january 5, 2011, 12:00:00

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!


More From » getelementsbyname

 Answers
9

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);
}
}
}

[#94362] Tuesday, January 4, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckenna

Total Points: 445
Total Questions: 109
Total Answers: 109

Location: Virgin Islands (U.S.)
Member since Sun, May 16, 2021
3 Years ago
;