Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output form results on same page

Tags:

javascript

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>
like image 503
brandozz Avatar asked Dec 07 '22 10:12

brandozz


1 Answers

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>​
like image 97
j08691 Avatar answered Dec 27 '22 09:12

j08691