2

I have a form with several submit buttons. I want my last button to handle the submit rather than the HTML5 spec'ed first button.

I can't change the html at this point and am fairly sure this requires JS. But when I've given it a shot I've gotten into nasty loops or dead code trying to prevent default behaviour and then fire my other button.

Has anyone done this before? jQuery is on the page if needed.

Thanks, Denis

Denis Hoctor
  • 2,597
  • 4
  • 33
  • 51

2 Answers2

3

Since you mentioned jQuery :)

If all you want to do is submit your form when a user presses the enter key, then

$(function() {
    $('body').keypress(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            $('#myForm').submit();
       }
    });
});

However, if you have different behavior/forms depending on which button is clicked and you want the enter key to trigger your last button's click event, then

$(function() {
    $('body').keypress(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            $('input[type="submit"]:last').click();
        }
    });
});
Nimrod
  • 1,316
  • 9
  • 14
  • That second example is what I'm after! I had the smae but was firing .submit() & .keypress() on it instead. Thanx An aside: I normally use window.event.keyCode, what the difference to e.which? – Denis Hoctor Feb 23 '11 at 06:06
  • jQuery's `e.which` returns the keyCode that was pressed and works cross-browser. – Nimrod Feb 23 '11 at 06:12
1

You should just change the input element's type attribute to button instead when you don't want it to submit the form. (I know you said you can't really change the HTML, but this is the best way)

<input type="button" name="mybutton" class="submit-button" value="I wont submit!" />

jQuery code:

$('.submit-button').click(function() {
  $('#secret-value-field').val($(this).val());
  $(this).parents('form').submit();
});

Or something along those lines.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • But they are required to submit back to the sever. The sever page forks based on their differing names. If I made the others buttons of type button they wouldn't work.... – Denis Hoctor Feb 23 '11 at 05:55
  • So then change them all to buttons and then add a click handler to submit the form, and possibly change a hidden input field's value for the server to switch based on. If this sounds like what you need I can edit my answer with code for it. – Andrew Marshall Feb 23 '11 at 05:58
  • In my case this doesn't help... the enter key still triggers the button (even though it does the button's thing instead of submitting the form). – Nathan Jun 15 '12 at 06:09