Marc Rasmussen
Marc Rasmussen

Reputation: 20555

jquery onclick runs twice

I have the following javascript when my script is loaded:

var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
    //removes the hover color from the previous selected
    current_selected_note.removeClass('hover active');
    // sets the currently selected equal to the selected note
    current_selected_note = $(this);
    // adds the hover active to the currently selected
    current_selected_note.addClass('hover active');
    //adds the title of the currently selected to the title input field
    $('#txt_new_note_title').val($(this).find('Strong').text());
    selected_note_id = $(this).get(0).id;
    getNote(selected_note_id);
    load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );

Now AFTER this is loaded i click one of my buttons which has the following javascript:

    $('#note-item-lists').on('click','.close',function(){
    var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
    if(r == true){
        deleteNote($(this));
       $( "#note-item-lists").find('li').first().click();
    }
})

    function deleteNote(button){
    var id = button.closest('li').get(0).id;
    $.ajax({
        type: 'POST',
        url: '/solo/ajax_delete',
        dataType: 'json',
        data: {
            id: id
        },
        success: function (data) {
        }
    });
    button.closest('li').remove();
}

When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again.

Anyone tried this before?

Upvotes: 0

Views: 90

Answers (2)

Amit
Amit

Reputation: 15387

Try this, It will call one time.

 $('#note-item-lists .close').on('click',function(){
          alert("Hello");      
 });

Upvotes: 2

CRABOLO
CRABOLO

Reputation: 8793

Try using .off()

$('#note-item-lists').on('click', '.list-group-item', function () {
    $(this).off();  //add this here

Upvotes: 0

Related Questions