Search code examples
jqueryform-submitkeyevent

Submit form with Enter - Cannot select previously entered value with arrow keys + Enter


I'm using a simple javascript to submit a form when the Enter key is pressed:

$("input").keypress(function (e) {
    if (e.which == 13) {
        $(this).closest("form").submit();
        return false;
    }
});

Now there is a problem with this.
Browsers remember what you have typed in text fields before.

So lets say I chose something from the "auto completion". I hit my down arrow key and hit enter, wanting to select a previously entered value. Then the forms obviously submits, due to the keypress event.

Is there even a way to solve this?


Solution

  • The keypress event is fired before the browser fills in the input field. Keep track of what's in the field before the user hits Enter, and you can tell if the value changed by some means other than a keypress. It won't submit if the user hit Enter to select an auto-filled value.

    This works in at least FF and Chrome:

    var typed = "";
    $(document).ready(function(){
      $("#input-field").keypress(function (e) {
        if (e.which == 13) {        
          if($("#input-field").val() != typed) {
            $(this).closest("form").submit();
            //alert($("#input-field").val());
            return false 
          }
        }
        typed = $("#input-field").val();
      });
    });