Loop and sum

S

staeri

I have an unknown number of textboxes which I want to sum. They are
named something like this:

"ctl00$ContentPlaceHolder1$DataList1$ctl03$DataList2$ctl03$txtSumB"

The only thing i know for sure is that "txtSumB" is somewhere in the
name. The page can contain anything from 1 to 50 textboxes.

Can someone please help me with a script which loops through all the
textboxes with "txtSumB" in the name and sums the values?

Very grateful for help!

Regards,

S
 
R

RobG

I have an unknown number of textboxes which I want to sum. They are
named something like this:

"ctl00$ContentPlaceHolder1$DataList1$ctl03$DataList2$ctl03$txtSumB"

The only thing i know for sure is that "txtSumB" is somewhere in the
name. The page can contain anything from 1 to 50 textboxes.

Can someone please help me with a script which loops through all the
textboxes with "txtSumB" in the name and sums the values?

Get the elements within the form, find those with a name that has the
string in it and add them up.

<script type="text/javascript">

function showTotal(form, totalEl)
{
var el, els = form.elements;
var sum = 0;

for (var i=0, num=els.length; i<num; ++i){
el = els;

if ('text' == el.type && /SumB/.test(el.name)){
sum += +el.value;
}
form.elements[totalEl].value = sum;
}
}
</script>

<form action=""><div>
<input type="text" name="ZugZug">ZugZug<br>
<input type="text" name="fooSumBxx">fooSumBxx<br>
<input type="text" name="barSumByy">barSumByy<br>
<input type="text" name="sueSumBzz">sueSumBzz<br>
<input type="text" name="formTotal" readonly>Total
<input type="button" value="Show total"
onclick="showTotal(this.form, 'formTotal');">
</div></form>


Note that you need to test the value of each input to see if it's a
number and suitable to be added before actually adding it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top