2

Based on this Stackoverflow question there seems to be no defined standard behaviour, or shared implementation across browsers, for hitting the [Enter] key in an HTML form field when multiple forms are present on the page. I'd like a jQuery solution that detects [Enter] on any form field, discovers its immediate enclosing form, and .click()'s that form's Submit button.

The end result is the form expected to be affected by the user is submitted in any browser when [Enter] is used on a multi-form page.

I'm looking for a generic solution, like a jQuery plugin, that can be applied to multiple websites having this problem and for it to immediately take effect to submit the expected form. I don't want to have to code conditional statements or alter them per form or website.

Optional Update:
For a more detailed scenario, consider each form has only one type=Submit button and that's the default/target button
Any other buttons on the form are type=button and not considered for submission.

Community
  • 1
  • 1
John K
  • 28,441
  • 31
  • 139
  • 229

3 Answers3

1

The usual even for detecting enter:

        $(document).keydown(function(objEvent) {
            if (objEvent.keyCode == 13) {
                 $('.click-button').click();
            }
        })

Inside of the objEvent variable there is a .target which you can use to see where the enter was pressed.

See fiddle here: http://jsfiddle.net/maniator/svzeq/ (try pressing enter when in an input)

Code from fiddle:

$(document).keydown(function(objEvent) {
    if (objEvent.keyCode == 13) {
        alert($(objEvent.target).parent()[0].id + " pressed enter");
    }
});
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

I'd do something like this:

$('input[type=text]').keydown(function(event){
   if(event.keyCode == 13){
   event.preventDefault();
   $(this).closest('form').submit();
   }
});

when the return key is pressed inside a input field of type text, the relative form is submitted (it doesn't click the submit button but it just submits the form)

EDIT - if you want to click the submit button you could do:

  $(this).closest('form').find('input[type=submit]').click()
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • Based on the first paragraph of this answer - http://stackoverflow.com/questions/925334/925387#925387 - I'd like the submit button to be considered activated/successful by using .click() instead of submit event, but I can easily adapt the script – John K Jun 27 '11 at 15:38
0

i use this helper function to set up my default enter behaviour:

function SetFormDefaultButton(formId, buttonId) {


    var formSelector = "#{0}".format(formId);
    var buttonSelector = "#{0}".format(buttonId);

    $(formSelector).find('input, select').live('keypress', function (event) {

        if (event.keyCode == 13) {
            event.preventDefault();
            $(buttonSelector).click().focus();

            return false;
        }
    });
}
Patricia
  • 7,752
  • 4
  • 37
  • 70