简体   繁体   中英

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

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?

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM