Search code examples
javascriptkeyevent

Javascript: escape key clears text in firefox


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?


Solution

  • 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/