开发者

jQuery - How to restrict input values for text box

I want to restr开发者_如何学Pythonict input in TextBox to be either 'Y' or 'N' (any case). How can this be done in jQuery.


I'm pretty sure that if keydown returns false, then the input is not allowed. 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

$("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 u r handling error on ur page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜