I'm trying to display form results on the same page as the form but when I click my "Get Total" button I see the result appear briefly then disappear. My result is off too, I'm trying to add my variables together but I'm getting a join instead.
<form id="percentageBiz" method="post">
<input type="text" id="sum1">
<input type="text" id="sum2">
<input type="submit" onclick="total()" value="Get Total">
<div id="display" style="height: 50px; width: 100%;"></div>
<script>
function total(){
var a = document.forms["percentageBiz"]["sum1"].value;
var b = document.forms["percentageBiz"]["sum2"].value;
//alert(a+b)
var display=document.getElementById("display")
display.innerHTML=a+b;
}
</script>
It's flashing because you're not doing anything to stop the form from submitting, and concatenating because you're not casting the values as numbers. Note you can use parseFloat if you're dealing with non-integers instead of parseInt as I used below.
Try this jsFiddle example.
function total(){
var a = document.forms["percentageBiz"]["sum1"].value;
var b = document.forms["percentageBiz"]["sum2"].value;
//alert(a+b)
var display=document.getElementById("display")
display.innerHTML=parseInt(a,10)+parseInt(b,10);
return false;
}
and
<form id="percentageBiz" method="post">
<input type="text" id="sum1">
<input type="text" id="sum2">
<input type="submit" onclick="return total()" value="Get Total">
</form>
<div id="display" style="height: 50px; width: 100%;"></div>
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