Allow only numbers into a input text box

2019-01-27 05:01发布

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

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-27 05:27

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>


However, I would recommend the unobtrusive style of writing JS using because it is good to keep the HTML semantic and away from pollution. You can execute the function on event handler that we would attach to this text box using vanilla JavaScript or jQuery.

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

// using classic addEventListener method:
document.getElementById('onlyNumbers').addEventListener('keypress', function(e){    allowNumbersOnly(e);
}, false);

//using jQuery
$(function(){
    $('#onlyNumbers2').keypress(function(e) {
       allowNumbersOnly(e); 
    });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
    <div>
      Using addEventListener: <input type="text" id="onlyNumbers" />
    </div>
    
    <div>
      Using jQuery: <input type="text" id="onlyNumbers2" />
    </div>
</body>
</html>

To restrict every character you can just simply use e.preventDefault().

Besides, you can also use return false instead but preventDefault() is better in this case and return false should be chosen wisely. It is good to know the difference between both of them.

查看更多
干净又极端
3楼-- · 2019-01-27 05:30

document.getElementById('rating').onkeypress = function() { return false; }

This will prevent the default behavior of keypresses on that element i.e. text showing up.

查看更多
登录 后发表回答