Reputation: 48963
I am working on a creditcard form that uses JavaScript.
Often times my clients will send me more money than I bill them for, so to make things easy and prevent me from losing out on potential money, I have a Price
field that shows the total that they will be billed. I have now added a Tip
field which will allow them to add on to that price.
Here is some JavaScript/jQuery I have so far that updates my price field when they enter in a tip value...
$('.price_tip').keyup(function() {
var tip = $('.price_tip').val();
var price = $('.price').val();
var total = parseInt(price) + parseInt(tip);
$('.price').val(total);
});
This works pretty good almost except, if I remove everything from my Tip input box, then my Total Price field becomes NaN.
I need to make sure that my Price field always shows at least what I am billing my client if a tip value is removed.
This is where I could use some help please?
UPDATE
Here is my latest attempt, it seems to work, I can remove everything from the tip box and my total price field does not go to NaN
now. I did discover another problem, if a non numeric item is entered, then it messes up.
I am not sure how to make sure it is a number value?
$('.price_tip').keyup(function() {
var tip = $('.price_tip').val();
if(tip < 1){
tip = 0;
}
var price = $('.price').val();
var total = parseInt(price) + parseInt(tip);
$('.price').val(total);
});
Upvotes: 0
Views: 87
Reputation: 51
Have you tried using the isNaN(variableName) function? This function will tell you if the content of variableName is an illegal number or not. So,
isNaN("123") will be false meaning it is not an illegal number isNaN("12/3") will be true, meaning it is an illegal number
Hope this helps
Upvotes: 1
Reputation: 446
When the tip input is empty, $('.price_tip').val()
returns an empty string, the subsequent parseInt
returns NaN, adding a number and NaN, results in NaN.
Check the result of parseInt via isNaN
and only if it is a number add it to total. If it is not a number, you'd also display it to the user, that the input is invalid.
Upvotes: 1