user749798
user749798

Reputation: 5380

Dynamically add columns with checkboxes to html table in form

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?

Upvotes: 1

Views: 857

Answers (1)

mozkomor05
mozkomor05

Reputation: 1427

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.

Upvotes: 1

Related Questions