1

I'm trying to create a table where rows/columns can be added dynamically, but am running into a problem with adding columns.

See JSFiddle here

http://jsfiddle.net/6r75zgoa/

The table itself starts as very simple. It has an "Add Row" button at the bottom and "Add Column" button in the first column:

<form name="myform" id="myform">
    <table id="tablegrid">
        <tr id="Row1">
            <td class="space">&nbsp;</td>
            <td>State 1<BR><button type="button" class="btnAddCol">Add Col</button>
    </br></td>
        </tr>
        <tr id="Row2">
            <td>
                <input type="text" placeholder="Name" name="Name" />
            </td>
            <td>
                <input type="checkbox" name="State1" />
            </td>
        </tr>
    </table>
    <button type="button" id="btnAdd">Add Row</button>
    </br>
    <input type="submit"></input>
</form>

The "Add Col" button in the first column adds columns.

Each new column should have an "Add Colu" button to add more columns. The code appends the "Add Col" button, but the new button does not work (only the first add col button works).

See Javascript below:

     $('#btnAdd').click(function () {
         var count = 1,
             first_row = $('#Row2');
         while (count-- > 0) first_row.clone().appendTo('#tablegrid');
     });


     var myform = $('#myform'),
         iter = 2;
     $('.btnAddCol').click(function () {
         myform.find('tr').each(function(){
           var trow = $(this);
             if(trow.index() === 0){
             trow.append('<td>State '+iter+'<BR><button type="button" class="btnAddCol">Add Col</button></td>');
             } else {
                 trow.append('<td><input type="checkbox" name="name'+iter+'"/></td>');
             }

         });
         iter += 1;
      });

What can I do to get the new "add col" buttons to work?

1
  • Why you need add column button for each column? What is your goal? 1 Add row and 1 add column buttons should be enough for the table, isn't it? Commented Oct 23, 2018 at 18:31

1 Answer 1

1

Change this:

$('.btnAddCol').click(function () {
    //code here
});

To:

$(document).on('click', '.btnAddCol', function () {
    //code here
});

In your code, when user click on button, only one event is fired. But in my example event is fired everytime when user clicks on the page. And the second parameter is the class that the clicked element must have.

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

1 Comment

Works great. Thank you.

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.