1

I have an input type text with some functionality. The text always has the focus but in the meantime the text can change. When you press the escape key something should close. I did bind a key event for that and it works fine. My problem is that in firefox the text always clears when pressing the escape key. You can test it here:

$('#asd').click(function() {
    $(this).val('huhu');
});

$('#asd').keydown(function(e) {
    if(e.which == 27) {
        e.preventDefault();
        return false;
    }
});

http://jsfiddle.net/hJ9th/1/

Click in the textfield and then press escape. The text disappears. I tried to prevent it but it's not working.

What can I do to prevent that?

user2170547
  • 361
  • 1
  • 3
  • 15

2 Answers2

1

Super dirty but I guess I'm using that:

$('#asd').click(function() {
    $(this).val('huhu');
});

$('#asd').keydown(function(e) {
    if(e.which == 27) {
        var $this = $(this);
        $this.blur();
        setTimeout(function() {
            $this.focus();
        }, 10);
    }
});

http://jsfiddle.net/hJ9th/2/

user2170547
  • 361
  • 1
  • 3
  • 15
-1

This is built in behavior in Firefox.

If you want to prevent it, you need to attach a JS/jQuery handler to intercept keydown events, and return false if the keydown is ESC.

An example is here.

Community
  • 1
  • 1
Codeman
  • 12,157
  • 10
  • 53
  • 91
  • Isn't it exactly the same solution as what user2170547 is already using as described in the question? Also your link does not lead to a `keydown` example. – Andrey Shchekin May 15 '13 at 00:56
  • @AndreyShchekin the only difference between the linked example would be to change keyup to keydown. I've experienced this behavior myself, and I'm not sure that this will fix it in all cases. I answered the question, not sure why you downvoted. – Codeman May 15 '13 at 01:15
  • jQuery handler on `keydown` returning `false` is already in the body of question -- why answer with the same thing? – Andrey Shchekin May 15 '13 at 04:03