Carles Company
Carles Company

Reputation: 7216

Keyboard submit via jQuery

llo, I have a form that has two submit buttons: one accept and one cancel:

<p>
    <input type="submit" name="accio" value="accept" class="default" />
    <input type="submit" name="accio" value="cancel" class="cancel" />
</p>

I want to submit the form with jQuery using the keyboard:

$(document).ready(function() {
    $("input[type=text]").focus();
    $("input[type=text]").keydown(function(e) {
            if ((e.keycode && e.keycode == 13) || (e.which && e.which == 13)) {
                $(".default").submit();
            }
            if ((e.keycode && e.keycode == 27) || (e.which && e.which == 27)) {
                $(".cancel").submit();
            }
        });
});

and I want the parameter accio to contain accept or cancel depending on the key pressed (I process it in the server)... It works in Firefox, but not in IE nor in Chrome. Where's my fault?

Update

Following @Sime's I got the following code:

$(document).ready(function() {
    $("input:text").focus();
    $("input:text").keydown(function(e) {
            if (e.which == 13) {
                $("#default").submit();
            }
            if (e.which == 27) {
                $("#cancel").submit();
            }
        });
});

but it's still not working... I think it's with the way I submit the form... Can't I call the submit method on a "input:submit" and expect that the correct values are passed on to the controller?

Upvotes: 1

Views: 967

Answers (2)

andres descalzo
andres descalzo

Reputation: 14967

try this:

$("input[type=text]").keydown(function(e) {
     if ((e.keycode && e.keycode == 13) || (e.which && e.which == 13)) {
        $(".default")[0].click();
     }
     if ((e.keycode && e.keycode == 27) || (e.which && e.which == 27)) {
         $(".cancel")[0].click();
     }
});

could you put a way to better identify the buttons.

$("p input.cancel")

UPDATE:

$(document).ready(function() {
    $("input:text").focus();
    $("input:text").keydown(function(e) {
            if (e.which == 13) {
                $("#default")[0].click();
            }
            if (e.which == 27) {
                $("#cancel")[0].click();
            }
        });
});

see this example

UPDATE II

this code functiona well in IE6 +, the correction is in the stopPropagation

$('input[type="text"]').keydown(function(ev) {

  if (ev.which == 13 || ev.which == 27) {

      ev.stopPropagation();
      if (ev.which == 13)
         $("#default")[0].click();

     if (ev.which == 27)
         $("#cancel")[0].click();

      return false
  }

});

Upvotes: 3

Fokko Driesprong
Fokko Driesprong

Reputation: 2250

Try the following:

$( '#myForm' ).submit();
$( '#mySubmitButton' ).click();

Upvotes: 0

Related Questions