简体   繁体   English

JavaScript输入类型编号限制为值1和2

[英]JavaScript Input Type Number Restricted to Values 1 and 2

Probably done with JavaScript. 可能是用JavaScript完成的。

See this Example from W3Schools 请参阅W3Schools的示例

<input type="number"  size="2" min="1" max="2">

Even with the Min and Max values set, you can still type in whatever number you want and it will accept that value. 即使设置了“最小值”和“最大值”,您仍然可以键入所需的任何数字,它将接受该值。 How do I restrict the user in this case so they can only enter 1 or 2, if they enter something different then it sends an alert and clears the field so the user can try again. 在这种情况下,如何限制用户,以便他们只能输入1或2,如果输入的内容不同,则会发送警报并清除该字段,以便用户可以重试。

Without using JS, you can set the pattern attribute of the input field so the user knows at least that what he/she put in is invalid. 在不使用JS的情况下,您可以设置input字段的pattern属性,以便用户至少知道他/她输入的内容无效。 This will not clear the field however. 但是,这不会清除该字段。

DEMO 演示

HTML 的HTML

<input type="number" size="2" min="1" max="2" pattern="[12]">

CSS 的CSS

input:invalid { color:red; border:2px solid red; }

For simplicity's sake, I'm adding an id to your input: 为了简单起见,我在您的输入中添加了一个id

<input type="number" id="myInput" size="2" min="1" max="2">

Then we can simply add an event listener: 然后我们可以简单地添加一个事件监听器:

document.querySelector('#myInput').addEventListener('input', function(e) {
  if (e.target.value !== '1' && e.target.value !== '2') {
    alert('Invalid number!');
    e.target.value = '';
    e.preventDefault();
  }
});

JSFiddle example JSFiddle示例

Keep in mind, it's rather jarring UX to use alert , I'm only using it here for an example. 请记住,使用alert是相当不便的UX,这里仅作为示例。 Instead, you may want to add an error class to the element or pop up a modal. 相反,您可能想要向元素添加error类或弹出模式。

If you don't mind having a standard error message on invalid input, you can also use: 如果您不介意在无效输入中显示标准错误消息,则还可以使用:

<input type="text" pattern="[1-2]">

Edit: If you add a "title" attribute to the input, you can set the error message you want. 编辑:如果在输入中添加“标题”属性,则可以设置所需的错误消息。

The example is using the HTML 5 input type number , which not all browsers support consistently. 该示例使用HTML 5输入类型数字 ,并非所有浏览器都一致支持。

You could limit this range using JavaScript, perhaps using jQuery. 您可以使用JavaScript或jQuery来限制此范围。 This is definitely an improvement over the code above, but in truth in a real-world application you accomplish this by using a framework component like AngularJS , Knockout , or jQuery Validator . 这绝对是对上面代码的改进,但是实际上,在实际应用程序中,您可以使用AngularJSKnockoutjQuery Validator之类的框架组件来完成此任务。 Using a framework like this will allow you to manage all of your validation in a central location and implement more complex logic involving multiple properties, such as "Value two must be greater than value one". 使用这样的框架将使您可以在中央位置管理所有验证,并实现涉及多个属性的更复杂的逻辑,例如“值二必须大于值一”。

You can use jQuery and checkValidity() method of the input: 您可以使用jQuery和输入的checkValidity()方法:

$('[name=points]').bind('keyup',function(){
  if (!$(this).get(0).checkValidity()) {
    $(this).val('');
  }
});

checkValidity() will only work in modern browsers. checkValidity()仅适用于现代浏览器。

Demo: http://www.bootply.com/125666 演示: http//www.bootply.com/125666

This is how <input type=number> is expected to work: it does not physically prevent the user from entering arbitrary data (well, it might, but it need not), but the control does not satisfy constraints upon form submission, if it does not match the requirements. 这就是预期<input type=number>起作用的方式:它实际上并不能阻止用户输入任意数据(可以,但不一定),但是该控件不能满足表单提交的约束(如果有的话)与要求不符。

If you want to let the user select between two alternatives only, use a checkbox, or two radio buttons, or a select element with two options. 如果只想让用户在两个备选方案之间进行选择,请使用复选框或两个单选按钮,或者使用带有两个选项的select元素。 The details depend on whether this should be an obligatory choice or optional and whether there is a default value. 详细信息取决于这是必须选择还是可选,以及是否具有默认值。

PS W3schools.com is bogus, in this issue, too. PS W3schools.com在这个问题上也是虚假的。 The example you link to (which is different from your code) is not strictly incorrect, just illogical and misleading. 链接到的示例(与您的代码不同)并非严格错误,只是不合逻辑且具有误导性。

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

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