开发者

Verifying all text boxes are numbers in JQuery

$('#save').click(function(){
    ($('input[type=text]').each(function () {
        if (isNaN($(this).val())) {
       开发者_开发知识库     alert("Some of your values were not entered correctly.");
            return 0;
        }
    });
});

I can't figure out why this isn't working. Any suggestions?

Edit: Sorry for the misleading title--I need to make sure the text boxes contain ONLY numbers.


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/


in this topic a lot of dicussions about checking the numbers in JS. I hope it will help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜