1

When I select a row on the table, then click my "Add row" button, one row is added. I then click on another row, then click "Add row", it adds two rows. Every time I click on another row, the number of rows added goes up as well. How do I make it so only one row is added every time?

I'm pretty sure its due to a click event inside of another click event but I'm not sure how to fix that issue.

My current event adding rows:

$(document).on('click', 'tr', function() {
    var t = $('#data-table').DataTable();
    $('#data-table').dataTable();


    $('#addbtn').on( 'click', function () {
        t.row.add( [ 
            'New Group'
         ] ).draw( false );

    } );

} );

1 Answer 1

2

Try this:

$(document).on('click', 'tr', function() {
 var t = $('#data-table').DataTable();
 $('#data-table').dataTable();


 $('#addbtn').on( 'click', function () {
    t.row.add( [ 
        'New Group'
     ] ).draw( false );
    //This removes the listener when you are done with it
    //And it will create another when you click again
    $( "#addbtn").off( "click" );

 });
});

or you could basically move that addbtn listener out of tr listener
Hope these work!

Sign up to request clarification or add additional context in comments.

9 Comments

Hmmm, still having the same problem unfortunately
I have updated the code would you use $( "#addBtn").detach( "click" ); instead
No change unfortunately.
or this $('#addBtn').off('click'); I am looking through jQuery document sorry for mistakes
No worries, I appreciate the help anyway! Still having same problem with off.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.