Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  136] [ 7]  / answers: 1 / hits: 24338  / 12 Years ago, fri, january 4, 2013, 12:00:00

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>

More From » javascript

 Answers
70

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>​

[#81074] Thursday, January 3, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;