GreatWebGuy Self-proclaimed greatness is a hard thing to prove.

24Apr/0827

Default html button submit on enter with JQuery

I basically needed the update button to be the default action on clicking enter in the form, but there were multiple submit buttons in my form and they weren't in the order I needed due to UI design. This was a quick and dirty solution to select an html submit button and make it the default when a user clicks enter from certain or all input elements on the form. It could be tweaked to give specific behavior to specific types of input boxes, such as invoking a tab on enter in between required elements, but the general idea is using jQuery to click the default button when the user hits enter.

$(function() {
	$("form input").keypress(function (e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$('button[type=submit] .default').click();
			return false;
		} else {
			return true;
		}
    });
});
Comments (27) Trackbacks (4)
  1. In using JSF we found that without the return false and return true lines in this example that Firefox worked and IE didn’t behave as we expected. In IE the form was submitted, but we didn’t get the expected action execution on the back end nor the expected JSF error message on the screen. Best I can tell, the return false intercepts the default IE behavior which is to submit the form via the form definition (if that makes sense) as opposed to “pushing the button” which JSF knows which action to call.

  2. I’m currently using jQuery 1.3.1. And to make it even more compatible with most of the common situations and less error prone, I’m using the following code:

    jQuery(document).ready(function() {
    $(“form input, form select”).live(‘keypress’, function (e) {
    if ($(this).parents(‘form’).find(‘button[type=submit].default, input[type=submit].default’).length <= 0)
    return true;

    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    $(this).parents(‘form’).find(‘button[type=submit].default, input[type=submit].default’).click();
    return false;
    } else {
    return true;
    }
    });
    });

    This uses live so it also will work on newly added elements. And will also work on select elements. And also works on multiple forms. So it searches for the parent form of the element and uses that to find the submit button. As well as button form as input form.

  3. This is realy good and worth to read. ,

  4. Very nice and useful tutorials for web designers,
    Thanks for posting.

  5. there may be a small problem with fields: When a dropdown is open, the user can navigate the options with the keyboard, and under normal circumstances press enter to select the marked option. With this script, however, the form is instantly submitted when he tries this, which is not desirable.

  6. in my case I decided to take the “put an invisible clone of the submit button as the first element of the form”-approach.

    That felt saver than to hack a script to try and detect the enter key (the key codes are not really formalized. A browser could send a different code for enter).

    Here’s what I used (specific to my page layout where the last button is the default button):

    $(‘form’).each(function(){
    var $f = $(this);
    $f.prepend($f.find(‘button:last’)
    .clone()
    .css({
    position: ‘absolute’,
    left: “-999px”,
    top: “-999px”,
    height: 0,
    width: 0
    })
    );
    });

    I would have preferred visibility: hidden or even display:none, but IE doesn’t play with that idea and only submits buttons it thinks are visible (even though that clone certainly isn’t).


  7. Philip Hofstetter:

    in my case I decided to take the “put an invisible clone of the submit button as the first element of the form”-approach.
    That felt saver than to hack a script to try and detect the enter key (the key codes are not really formalized. A browser could send a different code for enter).
    Here’s what I used (specific to my page layout where the last button is the default button):
    $(‘form’).each(function(){
    var $f = $(this);
    $f.prepend($f.find(‘button:last’)
    .clone()
    .css({
    position: ‘absolute’,
    left: “-999px”,
    top: “-999px”,
    height: 0,
    width: 0
    })
    );
    });
    I would have preferred visibility: hidden or even display:none, but IE doesn’t play with that idea and only submits buttons it thinks are visible (even though that clone certainly isn’t).


    Lars Peter Thomsen:

    there may be a small problem with fields: When a dropdown is open, the user can navigate the options with the keyboard, and under normal circumstances press enter to select the marked option. With this script, however, the form is instantly submitted when he tries this, which is not desirable.

  8. Thanks , It’s really good code i have just implement and it works for me ,,,, Thanks

  9. What I used was a lot more leaner and generic.
    (obviously with some assumptions)

    $(“form *”).keypress(function(e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    $(this).parents(‘form’).find(‘[type=submit]‘).eq(0).focusin().click();
    }
    });


  10. Bruce:

    In using JSF we found that without the return false and return true lines in this example that Firefox worked and IE didn’t behave as we expected. In IE the form was submitted, but we didn’t get the expected action execution on the back end nor the expected JSF error message on the screen. Best I can tell, the return false intercepts the default IE behavior which is to submit the form via the form definition (if that makes sense) as opposed to “pushing the button” which JSF knows which action to call.

  11. Some litte optimization.

    1) deleted “default” class jquery search
    2) jquery search performed only once (assigned to variable)

    $(document).ready(function() {
    $(‘form input, form select’).live(‘keypress’, function (e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    var btnSubmit = $(this).parents(‘form’).find(‘button[type=submit], input[type=submit]‘);
    if (btnSubmit.length <= 0)
    {
    return true;
    }
    else
    {
    btnSubmit.click();
    return false;
    }
    } else {
    return true;
    }
    });
    });


    Michiel:

    I’m currently using jQuery 1.3.1. And to make it even more compatible with most of the common situations and less error prone, I’m using the following code:

    jQuery(document).ready(function() {
    $(“form input, form select”).live(‘keypress’, function (e) {
    if ($(this).parents(‘form’).find(‘button[type=submit].default, input[type=submit].default’).length <= 0)
    return true;
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    $(this).parents(‘form’).find(‘button[type=submit].default, input[type=submit].default’).click();
    return false;
    } else {
    return true;
    }
    });
    });

    This uses live so it also will work on newly added elements. And will also work on select elements. And also works on multiple forms. So it searches for the parent form of the element and uses that to find the submit button. As well as button form as input form.


  12. Bruce:

    In using JSF we found that without the return false and return true lines in this example that Firefox worked and IE didn’t behave as we expected. In IE the form was submitted, but we didn’t get the expected action execution on the back end nor the expected JSF error message on the screen. Best I can tell, the return false intercepts the default IE behavior which is to submit the form via the form definition (if that makes sense) as opposed to “pushing the button” which JSF knows which action to call.

  13. These responses have all been really helpful. Here’s a similar version as a jQuery extension. Add it to your js library and use something like this on your page:

    $(‘.foo form’).clickButtonOnEnter();

    jQuery.fn.clickButtonOnEnter = function() {
    $(this).live(‘keypress’, function(e) {
    if ($(this).parents(‘form’).find(‘button[type=submit].default, input[type=submit].default’).length <= 0) {
    return true;
    }
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    $(this).parents(‘form’).find(‘button[type=submit].default, input[type=submit].default’).click();
    return false;
    } else {
    return true;
    }
    });
    }

  14. My slightly changed version.
    It finds the first button of type submit in the form and executes that button. (btw, this is also the default behavior in Firefox, but not in IE).


    $.fn.installDefaultButton = function() {

    $(this).live('keypress', function(e) {

    // Submit button found, test for enter key press.
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {

    // No submit button found, execute default action.
    if ($(this).closest('form').find('input[type=submit]:visible').size() <= 0) {
    return true;
    }

    // Find first submit button in form and submit.
    var defaultButton = $(this).closest('form').find('input[type=submit]:visible:first');
    defaultButton.click();
    return false;

    } else {
    return true;
    }
    });

    // Enable jQuery chaining.
    return this;
    };

  15. THANK YOU! I’m a JSF developer and this just saved my ass. Us JSF developers can only accomplish server-side action upon form submit if a button is clicked, so when the user uses the enter button to submit a form without clicking the button, it really screws us up. This has saved my project!

  16. I tweaked Rob’s suggestion a little. You can specify different selector for the default button. Now we only search the DOM once.

    This coffe script:

    # Pressing "Enter" key clicks defaultButton
    # selector: defaults to first Submit button, like FF.
    # Some browsers click first button (not necessarily Submit), by default.
    # Derived from: http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/#comment-614
    $.fn.defaultButton = (selector = 'input[type=submit]:visible:first') ->
    $(this).live('keypress', (e) ->
    # simply leave if Enter key was NOT pressed
    return true unless ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
    firstSubmit: $(this).closest('form').find(selector)
    if firstSumit
    firstSubmit.click()
    false
    else
    true
    )
    # Enable JQuery chaining
    return this

    Generated:

    $.fn.defaultButton = function(selector) {
    if (selector == null) {
    selector = 'input[type=submit]:visible:first';
    }
    $(this).live('keypress', function(e) {
    if (!((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13))) {
    return true;
    }
    ({
    firstSubmit: $(this).closest('form').find(selector)
    });
    if (firstSubmit) {
    firstSubmit.click();
    return false;
    } else {
    return true;
    }
    });
    return this;
    };

  17. Lost my formatting. argh. I used .
    Also, there's a typo in the coffee script: `if firstSumit` should be `if firstSubmit`. And... now that selector may indicate something other than the first Submit button, I will rename that.

  18. Really handy thanks, we have been looking for a way of doing this without using asp.

  19. Thanks for share. I’m ready use it for my code. :P

  20. @Matt Scilipoti: the generated JavaScript seemed to stumble upon an error at “firstSubmit”. I changed the following to fix it for me:

    This:
    ({
    firstSubmit: $(this).closest(‘form’).find(selector)
    });

    To this:
    firstSubmit = $(this).closest(‘form’).find(selector);

    It worked for me after the change. I don’t know enough JavaScript, jQuery or CoffeeScript to say exactly why, but I guess it has to do with the “object literal” feature of JavaScript. The initial “firstSubmit” was created as a *property* inside an anonymous object, so it wasn’t available as a variable name when “if (firstSubmit)” asked for it.

    Thanks for the code!

  21. Is there a way to get that without JavaScript? i mean having JavaScript disabled.

    Also not using CSS trick position:fixed, user can navigate not using author css.

    Thanks

  22. Haven’t tried it yet, but I guess this should work.

  23. I’ve tried this with javascript but wish there is a way to do it with css only.


Leave a comment