Javascript Code Disappears After Button Click
Solution 1:
That happens because your submit button actually does a form submit on some action and page is being refreshed. There are some ways to fix behavior, such as:
make your submit button just a button: <input type="button">
actually doesn't seem you need a form there
or add return false to onClick handler:
<buttontype="submit"onclick="calcSub(); return false;">Calculate</button><br>
Solution 2:
Be aware of another issue: You have to use parentheses around (input.value - subTotalCalc)
. Without parentheses, you're trying to add and subtract strings, which results in NaN
.
tax.innerHTML = "Tax:" + " " + "$" + (input.value - subTotalCalc);`
Solution 3:
Your form is getting submitted when you click on the button, so the values are getting calculated but are disappearing immediately as the page is re-loaded.
Try adding onsubmit='return false;'
to your form tag and the page re-load will be prevented.
Alternately you can change the button type to button
.
Check this fiddle.
Solution 4:
You need to prevent the form from being submitted. The form might be submitted by the user pressing enter when the form element is in focus, or by clicking the submit
button. Even if the onclick
event returns false, the submit event isn't altered.
I've taken the liberty of forking your fiddle:
Check the demo
window.addEventListener('load',function()
{
var input = document.getElementById('fld'),
subTotal = document.getElementById('sub-total'),
tax = document.getElementById('tax'),
total = document.getElementById('total'),
subTotalCalc;
document.getElementById('calcForm').addEventListener('submit',function(e)
{
e = e || window.event;
e.preventDefault();//prevent form's default behaviour
e.stopPropagation();//if submit was sent by clicking submit button, stop the event hereif (input.value === '' || input.value != +(input.value))
{
alert('Please enter valid subtotal (numeric)');
return;
}
subTotalCalc = input.value / 1.06;
subTotal.innerHTML = "Subtotal:" + " " + "$" + subTotalCalc;
tax.innerHTML = "Tax:" + " " + "$" + (input.value - subTotalCalc);
total.innerHTML = input.value;
},false)
},false);
I'd be happy to explain the code further if needs be...
Note that this doesn't fix the issue JS has with floating-point precision, if you're thinking about asking a follow-up question on that matter, check this fiddle first! I've added a simple toDecimal
function here:
var toDecimal = function(num, precision)
{
precision = precision || 2;
num = +(num || 0);
return ( Math.round(num*Math.pow(10, precision))
/ Math.pow(10,precision)
).toFixed(precision);
};
So first multiply by 10^n, round and divide to 10^n again to get the desired float. To avoid any issues that might occur still (though there shouldn't be any AFAIKT, I've added a toFixed(n)
call, too. This might be useful in case the rounded number is 213.00
Post a Comment for "Javascript Code Disappears After Button Click"