ben
ben

Reputation: 111

Why do I have to double click button before it works?

I need to add a single line to a table when the user clicks on the button and also have a remove button to remove the line that was added.

When clicking on the button, nothing happens. Only clicking on the button for the second time, the code works.

I am very new to HTML and Javascript, so the code I have obtained from the internet.

function addRows() {
    $('.splitBtn').on('click', function() {
        $(this).closest('tr').insertBefore($('<tr><td><button class="delBtn" style="width: 30px; padding: 0px;" onclick="deleteRow()">-</button></td><td></td><td></td><td></td></tr>').insertBefore($(this).closest('tr')));
        $(this).closest('tr').remove(1);
    });
}

I have included "$(this).closest('tr').remove(1);" later because the lines duplicated and incremented for some reason (not the issue now). I also noted that insertBefore and insertAfter is inverted (if I understand it correctly). InsertAfter adds rows on top of the current row and insertBefore adds rows below the current row.

I will be great if someone can assist to allow me to only have to click once to make the buttons work.

Upvotes: 2

Views: 1538

Answers (2)

ben
ben

Reputation: 111

I found the solution on JSFiddle http://jsfiddle.net/rplantiko/cDa3N/.

This piece of code:

$('.splitBtn').on('click', function() {

Must be replaced with this:

$(document).on("click", '.splitBtn', function () {

Upvotes: 1

Mohammed El Banyaoui
Mohammed El Banyaoui

Reputation: 527

use only

$('.splitBtn').on('click', function(){
    $(this).closest('tr').insertBefore($('<tr><td><button class="delBtn" style="width: 30px; padding: 0px;" onclick="deleteRow()">-</button></td><td></td><td></td><td></td></tr>').insertBefore($(this).closest('tr')));
    $(this).closest('tr').remove(1);
});

And remove onclick from the html code for the button

When you click for the first time your function addRows runs, this function add listener to the button, so the listener just start working after the first click so when you click for the 2nd time the listener add the row

or use the code bellow te remove jQuery listener and use only the function addRows onclick

function addRows(){
    $(this).closest('tr').insertBefore($('<tr><td><button class="delBtn" style="width: 30px; padding: 0px;" onclick="deleteRow()">-</button></td><td></td><td></td><td></td></tr>').insertBefore($(this).closest('tr')));
    $(this).closest('tr').remove(1);
}

Upvotes: 1

Related Questions