2

I have a form where I want to disable keyboard input. However I still want to postback the form as part of collection so adding the 'disabled' attribute isnt the solution for me.

I have added this code to make the input readonly:

 //code to not allow any changes to be made to input field
        $(".customreadonly").keydown(function () {
            return false;
        });

And then I set this class like this:

  $("#StartRRP").addClass('customreadonly');

However when I remove the class like this:

$("#StartRRP").removeClass('customreadonly');

The input still wont allow keyboard input. This seems to be trivial, what am I doing wrong ?

Thanks in advance...

2
  • In addition to the disabled attribute, there's also the readonly attribute. A field can have readonly set and it will still be submitted. Commented Aug 5, 2015 at 20:21
  • @Pointy you are right. But I also need unobtrusive validation to work. Readonly fields are ignored by this. For most uses, using readonly would be the right way to go about this. Commented Aug 5, 2015 at 20:42

1 Answer 1

5

When you attach the event directly to the jQuery object, it remains even after the initial selector to it is no longer valid(ie, class removed).

Either explicitly unbind

$("#StartRRP").removeClass('customreadonly');
$("#StartRRP").unbind('keydown');

or change your approach to use delegation

$(document).on("keydown", ".customreadonly", function () {
            return false;
        });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this was a very short and well explained answer. Thank you again for such a swift response.

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.