Know your ISP.

breath-hyenas
User #293650   177 posts
Forum Regular

I have the code below so far, and am sure there must be an easier way to automatically create the var fieldnames of AA, AB, AC etc and relate them to the <form> area, but I am stuck. Any ideas or better ways of doing this as there are going to be 80 or so fieldnames? I have AA, AB etc, but they can be anything as long as they relate to the form id.

<script type="text/javascript" language="javascript">
function getTotal(oForm)
{
var field, i = 0, total = 0, els = oForm.elements;
var fieldnames = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG' ];
for (i; i < fieldnames.length; ++i)
{
field = els[fieldnames[i]];
if (field.value != ' && isNaN(field.value))
{
alert('Please enter a valid number here.')
field.focus();
field.select();
return ';
}
else total += Number(field.value);
}
return ' ' + total;
}
</script>
</head>
<body>
<form>
<input id="AA" type="text" name="AA" value="" /><br />
<input id="AB" type="text" name="AB" value="" /><br />
<input id="AC" type="text" name="AC" value="" /><br />
<input id="AD" type="text" name="AD" value="" /><br />
<input id="AE" type="text" name="AE" value="" /><br />
<input id="AF" type="text" name="AF" value="" /><br />
<input id="AG" type="text" name="AG" value="" /><br />

<br />
<input id="total" type="text" name="total" value="" readonly="readonly" />
<input type="button" value="Get Total" onclick="total.value=getTotal(this.form)" />
<input type="reset" />
</form>

reference: whrl.pl/RccCIW
posted 2010-Mar-14, 9am AEST
User #213300   3203 posts
Whirlpool Forums Addict

jQuery.

You can wrap all those inputs in a fieldset, or a div, or put a class name against them.

Assuming you put a class name of 'total-inputs'.

$('.total-inputs').each(function(i, e)
{
if (e.val() != ' && isNaN(e.val()))
{
alert('Please enter a valid number here.')
e.focus();
return ';
}
});
reference: whrl.pl/RccCJG
posted 2010-Mar-14, 9am AEST
User #293650   177 posts
Forum Regular

Thanks for that. Actually, I wasn't thinking about jQuery and your post prompted me. I actually found this just in case anyone is trying to do what I'm doing.

It's a jQuery plugin:
http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm

reference: whrl.pl/RccC2r
posted 2010-Mar-14, 11am AEST
edited 2010-Mar-14, 11am AEST
Hosted by
Bulletproof Managed Hosting
Big numbers
1,668,891 threads
32,921,465 posts
3,365,326 whims sent
3,986 wiki topics
195 ISPs listed
10,178 broadband plans
1,268 modems & routers
59,837 features filled