What I want to do is have numbers inputted by user and the sum of the numbers returned. My logic is as follows:
And here is the code I have so far:
<script type='text/javascript'>
var val=document.getElementById('userInput').value;
var temp=val.split(" ");
function sum() {
for(var i=0, MISSING THIS BIT
document.getElementById('resultSum').innerHTML=MISSING THIS BIT;
}
</script>
<form name="input">
<textarea name="userInput" rows=20 cols=20></textarea>
<input name="Run" type=Button value="run" onClick="sum()">
<form name="resultSum"><input type=Text>
I admit with humility that this is mostly probably wrong and appreciate anybody's time and effort.
UPDATE: I have done as suggested and I get the following error on my code below:
Message: 'document.getElementById(...)' is null or not an object Line: 16 Char: 1 Code: 0
<html>
<script type='text/javascript'>
function sum(){
var val = document.getElementById('userInput').value;
var temp = val.split(" ");
var total = 0;
var v;
for(var i = 0; i < temp.length; i++) {
v = parseFloat(temp[i]);
if (!isNaN(v)) total += v;
}
document.getElementById('resultSum').innerHTML=total;
}
</script>
<form name="input">
<textarea name="userInput" rows=20 cols=20></textarea>
<input name="Run" type=Button value="run" onClick="sum()">
<form name="resultSum"><input type=text>
<html>
Any suggestions? Thanks to all for being comprehensive - I have read both examples and understand the process now!
You want a basic loop to convert and add each item.
I have also cleaned up your HTML a ton. You didn't have any proper closing tags. I have also changed all of the 'name' attributes to 'id' attributes so that 'getElementById' would work properly, which I missed on my first pass.
<html>
<head>
<script type='text/javascript'>
function sum(){
var val = document.getElementById('userInput').value;
var temp = val.split(" ");
var total = 0;
var v;
for(var i = 0; i < temp.length; i++) {
v = parseFloat(temp[i]);
if (!isNaN(v)) total += v;
}
document.getElementById('resultSumValue').value = total;
}
</script>
</head>
<body>
<form id="input">
<textarea id="userInput" rows=20 cols=20></textarea>
<input id="Run" type=Button value="run" onClick="sum()" />
</form>
<form id="resultSum">
<input id="resultSumValue" type="text" />
</form>
</body>
</html>
This will also ignore any values that are 'NaN' (Not a Number).
If you want the numbers to only be integers (no decimals), change parseFloat to parseInt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With