nickyfraggle
09-06-2008, 07: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>
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>