简体   繁体   English

jQuery-如何限制文本框的输入值

[英]jQuery - How to restrict input values for text box

I want to restrict input in TextBox to be either 'Y' or 'N' (any case). 我想将TextBox中的输入限制为“ Y”或“ N”(任何情况)。 How can this be done in jQuery. 如何在jQuery中完成。

I'm pretty sure that if keydown returns false, then the input is not allowed. 我非常确定,如果keydown返回false,则不允许输入。 You can do this by grabbing the key code from the event object. 您可以通过从事件对象中获取键代码来实现。 This doesn't prevent doing things like copy/pasting a value into the text box, though. 但是,这不会阻止执行将值复制/粘贴到文本框中的操作。 So a better option would be a select or radio button if you want to restrict the user's input. 因此,如果您想限制用户的输入,最好使用选择或单选按钮。

$("#some-selector").bind("keydown", function (e) {
  return e.keyCode == 89 || e.keyCode == 78
});

As you said this does not take care of the case of copy/paste a better alternative would be to attach a change event handler and then check if its an allowed char else flag an error 如您所说,这不能解决复制/粘贴的情况,更好的选择是附加更改事件处理程序,然后检查其是否允许的char else标志错误

$("some-selector").change( function () {
    var textBoxVal=$(this).val();
    if(textBoxVal!=='y' || textBoxVal!=='n')
        alert("Error");                   
});

Note:alerts jsut an example- add a different style to the textbox or however ur handling error on ur page. 注意:提示一个示例-向文本框添加其他样式,或者在您的页面上处理错误。

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

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