The isNaN
function checks for a specific value called NaN
[MDN], which is the result of trying to perform arithmetic operations on non-number objects. It doesn't check if a string is a number. How about a regular expression?
if (!/^\d+$/.test($(this).val())) {
// Not a number...
}
The above will accept positive integers. If you need to accept negative or floating point numbers, change the regular expression to:
/^-?\d+$/ <-- Accepts positive and negative integers.
/^\d+(\.\d+)?$/ <-- Accepts positive integers and floating point numbers
/^-?\d+(\.\d+)?$/ <-- Accepts positive and negative integers and fpn.
Also, if you return 0 from within each
, that stops the loop, but that doesn't prevent the click event from continuing on. You have invalid data, you need to call event.preventDefault()
to halt the click event. Something like this will do:
$('#save').click(function(event){
var badInputs = $('input:text').filter(function() {
return !$(this).val().match(/^\d+$/);
};
if (badInputs.length) {
alert('Some of your values were not entered correctly.');
event.preventDefault();
}
});
Working example: http://jsfiddle.net/FishBasketGordo/ER5Vj/