Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

javascript - Check if a textbox contains numbers only

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

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

1 Reply

0 votes
by (71.8m points)

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+" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...