简体   繁体   中英

Adding rows and columns to an HTML table using jQuery

I'm using jquery to dynamically add columns and rows to the table.

The problem I'm having is that I'm adding the rows with code as below:

        $('#colorgrid').append("<tr id='Row2' class='input-row'><td><input type='text' name='shade' placeholder='shade'/></td><td ><input type='checkbox' name='asdf'/></td><td ><input type='checkbox' name='shade'/></td><td ><input type='checkbox' name='color'/></td></tr>")

So after I add one column and then add one row, it is missing a checkbox. Please see screen shot below:

Ideally whenever new row is added I would like it to fill however many columns there are with checkboxes and fill the name attribute of the checkboxes with the column name.

Question

How can I add a new row such a way so that it is really dynamic and I'm not hardcoding the contents of the row. It should fill all the columns with checkboxes and name them corresponding to the columnheader.

在此处输入图片说明

You should look into JQuery's Clone function . You can clone the last or first row without actually hard-coding the elements that you will add. This will copy all the elements including the new column(s).

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

$('.hello').clone().appendTo('.container');

this should produce

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
  <div class="hello">Hello</div>
</div>

It is up to you to modify the name , id and value of each element (if needed) before doing the appendTo . You can use jQuery with that as well. To find each input element:

newRow.find('input').each(function () {
    var $inputElem = $(this);
    $inputElem.attr('id', 'newId'); //change this to something more dynamic
    $inputElem.attr('name', 'newName'); //change this to something more dynamic
}

Andy's answer is cleaner and you may want to do that while modifying the elements within it. However if it's less a case of "copy but different" and more "new row with certain parts copied", this fork might help .

The technique here involves creating a new row, then iterating through each of the desired table headers with jQuery's each method (specified here to select #Row1 th:not(.space) within the table, ie "the headers in #Row1 that aren't .space "), using jQuery's trim to get their inner text devoid of superfluous whitespace (newlines, indentation), and then appending a new cell and input with that value as a name for each.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM