Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to check if a textbox contains numbers only?

While googling I came across this. But I'm wondering if isNumeric can be used for this purpose or if there are more simpler ways of checking if a textbox has a numeric value.

var query = $('#myText').val();
if (parseFloat(query) == NaN) {
    alert("query is a string");
} else {
    alert("query is numeric");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
239 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can check if the user has entered only numbers using change event on input and regex.

$(document).ready(function() {
    $('#myText').on('change', function() {
        if (/^d+$/.test($(this).val())) {
            // Contain numbers only
        } else {
            // Contain other characters also
        }
    })
});

REGEX:

  1. /: Delimiters of regex
  2. ^: Starts with
  3. d: Any digit
  4. +: One or more of the preceding characters
  5. $: End

Regex Visualization:

enter image description here

Demo


If you want to allow only numbers, you can use input-number and pattern

<input type="number" pattern="d+" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...