I have a textbox below which is created through this code:
$('#txtWeight').each( function() {
var $this = $(this);
var $weightText = $("<input type='text' class='txtWeightRow' maxlength='5' onkeypress='return isNumberKey(event)'/>").attr('name',$this.attr('name'))
.attr('value',$this.val())
$weight.append($weightText);
});
What I want to know is that how is it suppose to be written that if the textbox is blank, then it should have a hidden value of 0?
Below is code which does the calculation between 100 and the number entered in the textbox:
function calculateTotal()
{
var totalweight = totalmarks;
$("#qandatbl td.weight input").each(function (i, elm){
totalweight = totalweight - parseInt($(elm).val(), 10);
});
$("#total-weight").text(totalweight);
}
td.weight input is the textbox.
totalmarks = 100.
Thanks
In the code that does the subtraction, you can treat an empty value as 0 by using the
Number()constructor (a typecast). Like this:Then it doesn’t matter what is in the textbox, the subtraction will work. If the value in the textbox is not a number (e.g. an empty string) it will be treated as the number zero, and the result of the subtraction will be 100 (not NaN).
In your code, just use
Number()instead ofparseInt():If you want just to avoid decimal numbers, you can even do parseInt after the Number (i.e.
totalweight = totalweight - parseInt(Number($(elm).val()), 10);).