Reputation: 425
I'm running into an error when performing a calculation on submit using javascript. The pay_amount input submits '1' and total_charged submits '4.95' regardless of what the value of pay_amount is.
Here is the html:
<form method="POST" action="example-post-url.php" autocomplete="off" name="form" id="form">
<input type="text" id="pay_amount" name="pay_amount" value="1,794.00"/>
<input type="hidden" id="total_charged" name="total_charged" />
<input type="submit" value="submit" onclick="submitCard();" id="submitButton"/>
</form>
Here is the javascript:
<script>
function submitCard(){
var payment = parseFloat(document.getElementById('pay_amount').value);
var fee = ((payment*0.035)+3.95);
var total = payment + fee;
document.getElementById('total_charged').value = total.toFixed(2);
document.form.submit();
}
</script>
I've tried replacing var payment with the code below thinking it was an issue with commas, but I'm still running into problems.
var payment = document.getElementById('pay_amount').value.replace(/,/g, '');
What in the world is going on here?
Upvotes: 0
Views: 178
Reputation: 773
Fortunately, this has nothing to do with the submit
event of the form, and more to do with how the string type of the value
attribute is being converted into a number for math operations.
Check out this JSFiddle for how to use parseFloat()
better.
Here is the important part:
parseFloat(document.getElementById('pay_amount').value.replace(',', ''));
Upvotes: 0
Reputation: 118289
try this:
<script>
function submitCard(){
var payment = parseFloat(document.getElementById('pay_amount').value);
var fee = ((payment*0.035)+3.95);
var total = payment + fee;
document.getElementById('total_charged').value = total.toFixed(2);
}
</script>
Upvotes: 1
Reputation: 413818
The parseFloat()
routine stops parsing when it sees something that's not part of a valid number. In your case, that's the comma.
When you change the code as you suggested in your post, you fix the comma problem but you leave the value as a string. If you combine the two — get rid of the comma and call parseFloat()
— it'll work better.
That said, if you're not going to be checking the payment and fee computation on the server, please post the URL for your e-commerce site once it's done.
Upvotes: 3
Reputation: 15387
Try this
<input type="button" value="submit" onclick="submitCard();" id="submitButton"/>
instead of
<input type="submit" value="submit" onclick="submitCard();" id="submitButton"/>
Upvotes: 1
Reputation: 5788
Try
document.forms[0].submit();
Instead of document.forms.submit()
which is what you have right now.
This should be changed regardless of whether it solves the problem as document.form
is undefined.
Upvotes: 0
Reputation: 2978
You should prevent the original submit
<form ... onsubmit="return false;" ...>
...
</form>
Upvotes: 1