开发者

isolate jquery keybind to a single focused element

How can I allow a form to be triggered with the user hits enter, but only if that field is in focus? This is what I have now, but pressing enter anywhere (obviously) triggers the form.

 jQuery(window).开发者_如何学Gobind('keypress', function(e){
   if ( e.keyCode == 13 ) {
     jQuery("#goform").click();
     e.preventDefault();
   }
 });


Try putting the .bind on the element, not the entire window:

jQuery('#elementID').bind('keypress', function(e){
   if ( e.keyCode == 13 ) {
     jQuery("#goform").click();
     e.preventDefault();
   }
 });

If your field has id elementID. Offcourse you can approach the field by name, tagname or using any other jQuery Selector.


You chould use the selector to select the form element and assign the keypress() method to that object:

$('#idOfFormInputElement').keypress(
    function(e){
        e.preventDefault();
        e.stopPropagation();
        if (e.keyCode == 13) {
            $(this).closest('form').submit();
        }
    });

If the element is dynamically added, then delegate() could be used instead:

$('#idOfFormElement').delegate('#idOfFormInputElement', 'keypress',
    function(e){
        e.preventDefault();
        e.stopPropagation();
        if (e.keyCode == 13) {
            $(this).closest('form').submit();
        }
    });


Use jQuery('#{insert-your-form-field-id}') instead of jQuery(window)


The 'e' parameter that gets passed to the callback function will contain details of what element fired the 'keypress' event -

e.target.id

http://api.jquery.com/event.target/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜