button click event is triggered after keypress using jQuery

被刻印的时光 ゝ 提交于 2019-12-10 19:01:36

问题


I have these codes

$('#search-button').keypress(function (e) {
   if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {            
        search();
   };
});

$('#search-button').bind('click', function () {
   search();
});

under the search module I have an alert, now whenever I press Enter when the button is in focus, the search() under the click event also triggers. Please help. Thanks.


回答1:


Pressing enter does fire the keypress event - but also triggers the button's 'click' event, so you get search called twice.

You don't need to add a handler for the enter key.




回答2:


    $(document).ready(function(e) {
$('form').bind('keypress', function(event){
    if(event.keyCode == 13)
    {
    event.preventDefault();
    $("#submitcat").click();
    }
});
$("#submitcat").click(function(){
alert("Ok");    
});
});



回答3:


Why do you put the keypress event on the button? Pressing Enter on it will trigger the click event anyway. You'll probably want to put the keypress event on the text input or drop it altogether.




回答4:


$(document).on('keypress',function(e) {
    if (e.keyCode == 13 || e.which == 13) {
        var identifier = e.target.id;
        console.log(e.target.id);
        $('#' + identifier).click();
    }
});


来源:https://stackoverflow.com/questions/3447050/button-click-event-is-triggered-after-keypress-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!