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
551 views
in Technique[技术] by (71.8m points)

html - Allow only numbers into a input text box

I have a number input text box and I want to allow the user to edit but do not want to allow the user to enter any other text except numbers. I want them only to be able to use the arrows on the number input box.

 <input type = "number" min="0" max="10" step="0.5"  input id="rating"   name = "rating" class = "login-input" placeholder = "Rating 1-5:" value="0">
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 achieve this by pure JavaScript. Create this function that you can reuse in your script.

function allowNumbersOnly(e) {
    var code = (e.which) ? e.which : e.keyCode;
    if (code > 31 && (code < 48 || code > 57)) {
        e.preventDefault();
    }
}

You may preferably call this onkeypress event handler.

<input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />

function allowNumbersOnly(e) {
    var code = (e.which) ? e.which : e.keyCode;
    if (code > 31 && (code < 48 || code > 57)) {
        e.preventDefault();
    }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
    Try editing in me:
    <input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />
</body>
</html>

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

...