checking if number entered is a digit in jquery

前端 未结 10 1682
遥遥无期
遥遥无期 2020-12-01 01:19

I have a simple textbox in which users enter number.
Does jQuery have a isDigit function that will allow me to show an alert box if users ente

相关标签:
10条回答
  • 2020-12-01 01:37
    var yourfield = $('fieldname').val();
    
    if($.isNumeric(yourfield)) { 
            console.log('IM A NUMBER');
    } else { 
            console.log('not a number');
    }
    

    JQUERY DOCS:

    https://api.jquery.com/jQuery.isNumeric/

    0 讨论(0)
  • 2020-12-01 01:42

    With jQuery's validation plugin you could do something like this, assuming that the form is called form and the value to validate is called nrInput

    $("form").validate({
                errorElement: "div",
                errorClass: "error-highlight",
                onblur: true,
                onsubmit: true,
                focusInvalid: true,
                rules:{
                    'nrInput': {
                        number: true,
                        required: true
                    }
                });
    

    This also handles decimal values.

    0 讨论(0)
  • 2020-12-01 01:45

    there is a simpler way of checking if a variable is an integer. you can use $.isNumeric() function. e.g.

    $.isNumeric( 10 );     // true
    

    this will return true but if you put a string in place of the 10, you will get false.

    I hope this works for you.

    0 讨论(0)
  • 2020-12-01 01:51

    I would suggest using regexes:

    var intRegex = /^\d+$/;
    var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
    
    var str = $('#myTextBox').val();
    if(intRegex.test(str) || floatRegex.test(str)) {
       alert('I am a number');
       ...
    }
    

    Or with a single regex as per @Platinum Azure's suggestion:

    var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
    var str = $('#myTextBox').val();
    if(numberRegex.test(str)) {
       alert('I am a number');
       ...
    }    
    
    0 讨论(0)
  • 2020-12-01 01:51

    jQuery is a set of JavaScript functions, right? So you could use JavaScript's regular expression support to validate the string. You can put this in a jQuery callback if you like, too, since those just take anonymously-declared function bodies and the functions are still JavaScript.

    Link: http://www.regular-expressions.info/javascript.html

    0 讨论(0)
  • 2020-12-01 01:53

    Following script can be used to check whether value is valid integer or not.

      function myFunction() {
        var a = parseInt("10000000");
        if (!isNaN(a) && a <= 2147483647 && a >= -2147483647){
        alert("is integer"); 
        } else {
         alert("not integer"); 
        }
    }
    
    0 讨论(0)
提交回复
热议问题