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

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

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

1 Answer

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>

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

548k questions

547k answers

4 comments

86.3k users

...