I’m using this to calculate the amount and to get the percent off based on the two textboxes. This works except I get a NaN when the second box is empty. As soon as I type in the second box it works fine
$('#deal_price').keyup(function() {
var num1 = $("#deal_retail").val(),
num2 = $("#deal_price").val(),
result = parseInt(num1, 10) - parseInt(num2, 10);
result_percentage = result / parseInt(num1, 10);
result_percentage = parseFloat(result_percentage).toFixed(2);
result_percentage = result_percentage * 100;
$(".result_save").text(result);
$(".result_percentage").text(result_percentage);
});
I tried replacing the result_save and result_percentage with a empty else if as shown below
if (result_percentage == '' || result == '') { }
else {
$(".result_save").text(result);
$(".result_percentage").text(result_percentage);
}
I don’t think I’m getting how to use the empty option. Is there something like php has
if(empty($myvar)){
// nothing
}
else {
$dosomething = '2';
}
When you want to validate a number, use
isNaN.Also, instead of using
if(..){}else{ ... }, you can also use the unary!:if(!..){...}: