Adding Text Boxes auto

K

Kevin Davis

Hi there,

I have a bunch of text boxes that I want to add up and have another
text box that would show the total each time there is a number. Is
there a way to do that in JavaScript??

Thanks!
 
J

Jeremy J Starcher

Hi there,

I have a bunch of text boxes that I want to add up and have another text
box that would show the total each time there is a number. Is there a
way to do that in JavaScript??

Thanks!

Sure is.

Assuming that one is using a proper form with sensibly named (or ID'd)
INPUT elements, it is rather trivial to do.

Trivial enough it would make a nice homework assignment.
 
G

Gregor Kofler

Am 2010-07-01 18:19, Kevin Davis meinte:
Hi there,

I have a bunch of text boxes that I want to add up and have another
text box that would show the total each time there is a number. Is
there a way to do that in JavaScript??
Definitely.

Thanks!

You are welcome.
 
S

SAM

Le 7/1/10 6:19 PM, Kevin Davis a écrit :
Hi there,

I have a bunch of text boxes that I want to add up and have another
text box that would show the total each time there is a number. Is
there a way to do that in JavaScript??

Yes, of course.


In each input tag you add an attribute 'onchange' with a JS function to
do the addition.

Take care that imput's value are strings
(that can't be mathematically added)

Better if this function can admit the coma in decimal separator.

About numbers in JS :
<http://jibbering.com/faq/#numbers>


Non documented example :

<script type="text/javascript">

function total() {
var f = document.forms[0],
n = f.length - 3,
sum = 0,
numJS = function(num) {
return num.replace(/,(\d{1,2})$/,'.$1')*1; };
while(n--)
if ( f[n].type == 'text' &&
f[n].value.length > 0 )
if( !!numJS(f[n].value)/2 ) sum += numJS(f[n].value);
else {
alert('You didn\'t enter a number/n'+
'thousand separator not allowed');
sum = 'error';
setTimeout( function() {
f[n].focus();
f[n].select();
},0);
break
}
f['result'].value = sum;
return (sum == 'error');
}

</script>
</head>
<body>
<form action="test.htm" onsubmit="return total()">
<p>price: <input onchange="total()"></p>
<p>price: <input onchange="total()"></p>
<p>price: <input onchange="total()"></p>
<p>price: <input onchange="total()"></p>
<p>price: <input onchange="total()"></p>
<hr>
<p>total: <input name="result"></p>
<p style="border:1px solid;text-align:right">
<input type="reset"> <input type="submit">
</p>
</form>
 

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,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top