简体   繁体   English

javaScript - 数字输入 - 接受特定数字

[英]javaScript - number input - accept specific numbers

I have 5 inputs with type 'number'.我有 5 个类型为“数字”的输入。 max value to be entered by the user is '5'.用户输入的最大值为“5”。
I want if the user enter for example '4' in the first input field .我想如果用户在第一个输入字段中输入例如“4”。 he can't submit this number again in the other fields.他无法在其他字段中再次提交此号码。

or he can but then an message pop up to alert him.或者他可以,但随后会弹出一条消息提醒他。
it 'd be great if the alert is built in the browser like when he enter a number that more than the 'max' the field get red as a wrong assignment.如果警报是在浏览器中构建的,就像当他输入一个超过“最大值”的数字时,该字段会因错误分配而变红,那就太好了。

I can make an array and when the user submit an value I check if that value in the array and if not I push it in the array but then I 'll have to make an alert design.我可以创建一个数组,当用户提交一个值时,我检查该值是否在数组中,如果没有,则将其推送到数组中,但随后我必须进行警报设计。

I just looking for smart and easy solution.我只是在寻找智能而简单的解决方案。

<input type='number' max = '5' onchange = 'change(this)'>
<input type='number' max = '5' onchange = 'change(this)'>
<input type='number' max = '5' onchange = 'change(this)'>
<input type='number' max = '5' onchange = 'change(this)'>
<input type='number' max = '5' onchange = 'change(this)'>

function change(it)
{
  // what shoult I do ?!...

}

thanks.谢谢。

You can use jquery and compare value of fields with each other upon change.您可以使用 jquery 并在更改时相互比较字段的值。 See this answer:看到这个答案:

https://stackoverflow.com/a/30307040/1333744 https://stackoverflow.com/a/30307040/1333744

What you can do is, give every input a class, lets say 'foo' .你可以做的是,给每个输入一个类,让我们说 'foo' 。

Then the JQuery goes as:然后 JQuery 变成:

$(".foo").on('change', function () {
    var inputNumber = $(this).val();
    if (inputNumber > 5) {
    alert("Can't enter more than 5! Sorry");
    $(this).val(5);
    } else {
     var array = [];
        $siblings = $(this).siblings();
        $.each($siblings, function (key, value) {
           array.push($(value).val()); 
        });
if ($.inArray($(this).val(), array) !== -1)
    {
        alert("You have already entered that number");
    }
    }
});

HTML: HTML:

<input type='number' max = '5' class='foo'>
<input type='number' max = '5' class='foo'>
<input type='number' max = '5' class='foo'>
<input type='number' max = '5' class='foo'>
<input type='number' max = '5' class='foo'>

If you don't want to use jQuery, then go on, convert the jQuery to Javascript by looking at the code provided.如果您不想使用 jQuery,请继续,通过查看提供的代码将 jQuery 转换为 Javascript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM