开发者

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(fu开发者_如何学Pythonnction() {
    $("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?


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
  }

});


Try the following:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜