Sam
Sam

Reputation: 6552

How do I submit forms with the Enter key without a submit button

I have jQuery go though all the submit buttons with the class button, and turn them each into an anchor element with the class button.

$("input.button").each(function(i) {

    var anchorButton = $("<a class='"+this.className+"' href='#'>"+this.value+"</a>")



    anchorButton.click(function(eventObject) {

        $(this).blur().prev("input.hidden").click();

        return false;

    });



    $(this)

        .after(anchorButton)

        .addClass("hidden")

        .removeClass("button pill-left pill-center pill-right");

});

I can then style the anchor element with CSS, cross-browser-ly. There's only one problem. Whenever I press the Enter key on form input elements, the form doesn't submit. However, if I un-hide the submit button, it works again. In conclusion, I can't get the Enter/Return key to submit the form unless I have a submit button visible (display != none).

How can I get the form to submit when I press Enter when I have the submit button hidden?

Upvotes: 2

Views: 4202

Answers (4)

Andreas Bonini
Andreas Bonini

Reputation: 44742

$("input.button").keydown(function(event) {
   if(event.keyCode == 13)
      $("...find the form...").submit();
});

This should work.

If it doesn't try this:

   $("..find the input button you hide..").css('position', 'absolute')
         .css('top', '-1000px');

This is better than the proposed visibility: hidden solutions since if you set the visibility to hidden the button will still "take up space".

Upvotes: 3

Marcel Korpel
Marcel Korpel

Reputation: 21763

Just use an ordinary form in your HTML, including a submit action attribute. Then you'll get the browser's default behaviour and pressing Enter within the form will submit it. Then you don't have to use jQuery to bind event handlers to all your submit buttons.

You can test it with this JSBin.

Upvotes: 1

Roopesh Shenoy
Roopesh Shenoy

Reputation: 3447

Try visibility=hidden

Upvotes: -1

Rupert Madden-Abbott
Rupert Madden-Abbott

Reputation: 13278

Have you tried changing the visibility to hidden instead of display to none?

Upvotes: -1

Related Questions