...

View Full Version : adding up text boxes



nickyfraggle
09-06-2008, 08:17 PM
Hello,

I am trying to add up the values of dynamically created textboxes.

I'm using php to create the text boxes depending on the options a user selects. Each box is called number.

I am trying to use JavaScript to add up the values of these boxes. It's working on natural numbers, but not on decimals.

Any idea why? It just says NaN which I assume is JS saying I can't do it!

Thanks,

Nicky


<script language=javascript>
function add() {
var sum = 0;
var valid = true;
var inputs = document.getElementsByName( 'number');
for(i =0; i < inputs.length; i++) {
if( inputs[i].value.match( /(^(0|[1-9][0-9]*)$)|((^(0?|[1-9][0-9]*)\.(0*[1-9][0-9]*)$)|(^[1-9]+[0-9]*\.0+$)|(^0\.0+$))/ )) {
sum+=parseFloat(RegExp.$1);
}
else {valid=false;}
}
if(valid) {
document.getElementById( 'sum').value = sum;
}
else{
alert("Please enter numbers only");
}
}
</script>

mrhoo
09-06-2008, 08:46 PM
what do you mean by parseFloat(RegExp.$1)?

nickyfraggle
09-06-2008, 09:08 PM
That was my attempt to add up decimal numbers. I followed a tutorial online, and it had parseInt there. I changed it to parseFloat to try to get it to understand the decimal place.

I know little about Javascript, so if you have another way of doing this I am all ears. Or point me to a tutorial...

Thanks

Philip M
09-07-2008, 09:59 AM
<script type = "text/javascript">
function add() {
var sumtot = 0;
var valid = true;
var inputs = document.getElementsByName('number');
for(i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i]) {
alert ("Please enter numbers only");
valid = false;
return valid;
}
sumtot = sumtot + parseFloat(inputs[i]);
}
if (valid) {
document.getElementById('sum').value = sumtot;
}
}
</script>


Note: change variable sum to sumtot.
It is never a good idea to use variable or function name which is the same as an element name or ID. You should also avoid giving names or id's to your variables/functions/arguments/forms words which are JavaScript methods/attributes such as 'name' or 'id' or 'value' or 'checked' or 'submit' or 'replace' or 'parseInt'.



We have been asked to correct our report on the wedding last week. On return from honeymoon the happy couple will be staying at The Old Manse and not as we stated at the home of the bridegroom's father.

nickyfraggle
09-07-2008, 11:30 PM
Thank you Phil. That's really appreciated.

Nicky



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum