USER_8675309
USER_8675309

Reputation: 893

jquery on('click', function()) triggering unexpectedly

I am having a brain fart today or something, because when i set up an on('click') event it is firing like it has been clicked.

var myJsFunctions = {
    confirmDelete: function (index) {
        $('#deleteRecipient').modal('show');
        $('#confirmRecipientDeletion').on('click',myJsFunctions.deleteRecipient(index));
    },

    deleteRecipient: function (index) {
        $('#deleteRecipient').modal('hide');
        $('#recipientIsDeleted_' + index).val(true);
        $('#recipient_' + index).hide();
    }
}

but when i click the button that fires confirmDelete, it runs all the way through the myJsFunctions.deleteRecipient as well.

Upvotes: 1

Views: 80

Answers (2)

Lalji Nakum
Lalji Nakum

Reputation: 380

You have made the mistake in on click jquery syntax. Change you code like this :

var myJsFunctions = {
confirmDelete: function (index) {
    $('#deleteRecipient').modal('show');
    $('#confirmRecipientDeletion').on('click',function(){
       myJsFunctions.deleteRecipient(index);
    });
},

deleteRecipient: function (index) {
    $('#deleteRecipient').modal('hide');
    $('#recipientIsDeleted_' + index).val(true);
    $('#recipient_' + index).hide();
}

}

Upvotes: 0

antyrat
antyrat

Reputation: 27765

This happens because you actually invoking your function and you pass as a handler function execution result from return statement.

You should pass function handler instead:

$('#confirmRecipientDeletion').on('click', function() {
    myJsFunctions.deleteRecipient(index);
});

Upvotes: 5

Related Questions