jQuery 输入文本只接受 1-10 之间的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20277927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:05:07  来源:igfitidea点击:

input text only accepts number from 1- 10

jqueryhtmljquery-uijquery-mobile

提问by Udit Bhardwaj

i have an input text where i want to set value to only number from 1 - 10 only when the user types a value that is more than the text box will change it to 10 or when less than 0 the text will change to 0.and the text box will also not accept other values than number i used the code below for this but its not working it even accepts letters and no matter how what value i put in it it accepts the value what am i missing in this input text. is there a need of js just for this kind of problem?

我有一个输入文本,我想将值设置为仅 1 - 10 之间的数字,仅当用户键入的值大于文本框时才会将其更改为 10,或者当小于 0 时,文本将更改为 0.and文本框也不会接受除数字以外的其他值,我为此使用了下面的代码,但它不工作它甚至接受字母,无论我输入什么值,它都接受我在此输入文本中缺少的值。是否需要js来解决这种问题?

<input type="number" min="0" max="10"/>

回答by Udit Bhardwaj

using min=1and max=10will work only when user gives input using arrows not when he/she writes in the input box. So you can use this script in combination with min and max

using min=1andmax=10仅在用户使用箭头输入时才起作用,而不是在他/她在输入框中书写时起作用。所以你可以结合使用这个脚本min and max

<input type="number" value="1" min="1" max="10">

script

脚本

var t = false

$('input').focus(function () {
var $this = $(this)

t = setInterval(

function () {
    if (($this.val() < 1 || $this.val() > 10) && $this.val().length != 0) {
        if ($this.val() < 1) {
            $this.val(1)
        }

        if ($this.val() > 10) {
            $this.val(10)
        }

    }
}, 50)
})

$('input').blur(function () {
    if (t != false) {
    window.clearInterval(t)
    t = false;
    }
})

DEMO

演示

回答by Orlo

You have to use JS or jQuery, if you want to disable user from typing anything but numbers.

如果您想禁止用户输入数字以外的任何内容,您必须使用 JS 或 jQuery。

try the following:

尝试以下操作:

Only numbers please: 
<input type="number" min="1" max="10" id="someid" onkeypress="return isNumberKey(event)" /> 

<script>
function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var num = document.getElementById('someid').value;
    if ((charCode > 31 && (charCode < 48 || charCode > 57)) || (num > 10)){
        if (num > 10){
          alert('choose number from 1-10');    
        }
        return false;
    }else{
        return true;
    }
}   
</script>

http://jsfiddle.net/3F5rd/1/

http://jsfiddle.net/3F5rd/1/