1

I want to restrict input in TextBox to be either 'Y' or 'N' (any case). How can this be done in jQuery.

1
  • 2
    Just out of curiosity, why won't you use a single checkbox for that? Commented Feb 24, 2011 at 1:26

2 Answers 2

5

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
});
Sign up to request clarification or add additional context in comments.

3 Comments

You may want to limit it to only one character too (at least that is what I interpreted from the OP). +1
@DrStrangeLove: In fact, jQuery recommends that you use event.which, since it normalizes the keyCode/charCode properties: api.jquery.com/event.which
If you want to get the actual char rather than the code, you can use String.fromCharCode( e.keyCode );
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.