This code is inside a jquery mobile form. It adds up the numbers and displays the total in a disabled text box. When the the total is 100, the continue (submit) button is enabled.
The session var code properly puts in zeroes when there isn’t a value.
Problem:
Sometimes people will type a number after the zero (eg: 0100).
It seems like this, combined with erasing a number will cause the numbers not to add up properly.
I could use your assistance with:
Getting rid of the random bugginess in calculating the total, especially when the value is cleared. Should I be using parseInt instead?
Thanks in advance.
<script>
$(document).ready(function() {
<?php
if (!isset($_SESSION['num1'])) {
echo "$('#num1').val(0);";
}
if (!isset($_SESSION['num2'])) {
echo "$('#num2').val(0);";
}
if (!isset($_SESSION['num3'])) {
echo "$('#num3').val(0);";
}
if (!isset($_SESSION['num4'])) {
echo "$('#num4').val(0);";
}
?>
//to handle previously entered values if back button used: <br/>
var tot = ($('#num1').val() - 0) +
($('#num2').val() - 0) +
($('#num3').val() -0) +
($('#num4').val() - 0);
$('#total').val(tot);
if (tot==100) {
$('#continue').removeAttr('disabled');
} else {
$('#continue').attr("disabled","disabled");
}
//to handle numbers on update.
$('input[name^="int"]').keypress(function() {
var tot = ($('#num1').val() - 0) +
($('#num2').val() - 0) +
($('#num3').val() -0) +
($('#num4').val() - 0);
$('#total').val(tot);
if (tot==100) {
$('#continue').removeAttr("disabled");
} else {
$('#continue').attr("disabled","disabled");
}
});
try with
parseInt($('#num').val(),10)instead of$('#num').val() - 0to transform the strings to numbers