Skip to content Skip to sidebar Skip to footer

Why Is JQuery Click Event Firing Multiple Times

I have this sample code here http://jsfiddle.net/DBBUL/10/ $(document).ready(function ($) { $('.creategene').click(function () { $('#confirmCreateModal').modal();

Solution 1:

Because you are binding it multiple times. Click event inside a click event means every time you click, a new click event is being bound on top of the previously bound events. Do not bind click events inside of click events unless the click event creates the element. There's also no need to re-initialize the modal over and over.

$(document).ready(function ($) {

    $('#confirmCreateModal').modal({show: false});

    $('#confirmCreateYes').click(function () {
        $('#confirmCreateModal').modal('hide');

        var test = "123";
        alert(test);
        console.log(test);             
    });

    $('.creategene').click(function () {

        $('#confirmCreateModal').modal('show');

    });
});

Demo


Solution 2:

change the code like this

$(document).ready(function ($) {

    $('.creategene').click(function () {

        $('#confirmCreateModal').modal();


    });
    $('#confirmCreateYes').click(function () {
            $('#confirmCreateModal').modal('hide');

            var test = "123";
            alert(test);
            console.log(test);             
        });
});

fiddle

You dont have to bind $('#confirmCreateYes').click in each button click.


Solution 3:

You can try this also -

$("#confirmCreateYes").unbind().click(function() {
//Stuff
});

Solution 4:

Add this to your code:

$( "#confirmCreateYes").unbind( "click" );

Like this:

$(document).ready(function ($) {

$('.creategene').click(function () {

    $('#confirmCreateModal').modal();

    $('#confirmCreateYes').click(function () {
        $('#confirmCreateModal').modal('hide');

        var test = "123";
        alert(test);
        console.log(test);
        $( "#confirmCreateYes").unbind( "click" );
    });
});

});

It will unbind the event, so that it isn't bound on top of the previous event. This allows the event only to fire within the original click event.

This is not a good method. It will unbind all click events attached to the element. I will leave it here for learning purposes.


Post a Comment for "Why Is JQuery Click Event Firing Multiple Times"