views:

92

answers:

2

I have an input (outside form) that captures name of an image. User should fill in a new name and hit enter. Ajax callback renames the image. This works.

I'd like to add ability to 'reset' the input content when the user presses escape (#27). But I'm not able to fill the value of the input with my value.

The code is

<input id="escapeInput" value="this is test" /> <input type="button" id="setDetaultToEscapeInput" value="Set default" />

jQuery(document).ready(function() {
 jQuery("#escapeInput").keydown(function(evt) {
  if (evt.keyCode == 27) {
   var input = jQuery(this);
   input.val('some default value') // doesn't work
   input[0].value = 'some default value 2'; // doesn't work
   input.parent().append('changed');
  }
 });
 jQuery("#setDetaultToEscapeInput").click(function() {
  var input = jQuery("#escapeInput");
  input.val('some default value') // works ok
 });
});

The interesting thing is that if I test e.g. for 'A' character ( if (evt.keyCode == 65)), the code works. Any idea how to handle it? It doesn't work only in FF (Opera and IE8 are OK).

+2  A: 

Try using the keyup event instead.

$(function() {
    $("#escapeInput").keyup(function(e) {
        if (e.keyCode == 27) {
            $(this).val("some default value");
        }
    });
});
Joe Chung
Very easy to change and it works, thx!
stej
+1  A: 

Try this

     $(document).ready(function() {
            $("#escapeInput").keypress(function(evt) {
                    var keycode = null;
                    if(evt.keyCode) {
                         keycode = evt.keyCode;
                    } else {
                         keycode = evt.which;
                    }
                    if (keycode == 27) {
             $(this).val("some default value");
             }
            });
        });
Arun P Johny