Why does my button click twice in jquery if I put it in submitHandler?

不羁的心 提交于 2019-12-13 02:33:36

问题


I have a short form, you can see it here http://jsfiddle.net/azxpckg5/1/

and I have a problem - the way to reproduce it is to click the save button. Then there will appear another button called submit. when user clicks it - it disappears and it's fine. But when user repeats this procedure (clicks save again and submit again - he can see that the last click was repeated twice. I believe the error might be somewhere here:

submitHandler: function (form) {
        alert("here!");
        $(".overlay-boxify2").toggleClass("open");
        $('#submitcForm').click(function() {
   // 
         $(".overlay-boxify2").toggleClass("open");
            alert("hegdsgsd");
        });
        return false;
    }

but to be honest I don't know how to fix it and what can be the issue. Can you help me with that?


回答1:


The issue is because you're attaching another click event handler to the #submitcForm button on every submission of the form (which happens when #saveBtn is clicked. Move the click handler outside of the validate() call and your code will work as you require.

$('#invoiceForm').validate({
    // settings...
});

$('#submitcForm').click(function () {
    $(".overlay-boxify2").toggleClass("open");
});

Updated fiddle




回答2:


Use .off() to prevent attaching multiple click eventListener on your button

submitHandler: function (form) {
    alert("here!");
    $(".overlay-boxify2").toggleClass("open");
    $('#submitcForm').off().click(function() { // see the use of .off()
        $(".overlay-boxify2").toggleClass("open");
        alert("hegdsgsd");
    });
    return false;
}

See more about .off()



来源:https://stackoverflow.com/questions/33550020/why-does-my-button-click-twice-in-jquery-if-i-put-it-in-submithandler

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