简体   繁体   中英

Adding td dynamically to html table at specific position using javascript

I have a HTML table in which a few td's are fixed and the rest are dynamic. So as of now (when all fields are static), the table looks like this

label1  tb1 | label2 tb2 | label3 tb3 | label4 tb4

Label Names and corresponding textbox values would both be dynamic.I have fetched the dynamic values from the table and stored them in a Javascript array. I now need to display those stored values by appending them to the static table present above.

But there's a condition in this. The dynamic fields need to be appended at a specific position. They need to be added after tb3.

Since one row can contain max of 4 elements, so any additional fields need to be pushed to next row. For Eg: If I get 3 dynamic td's from the database, then the new table needs to look like

label1 tb1         |label2 tb2         |label 3 tb3 |dynalabel1 dynatb1
dynalabel2 dynatb2 |dynalabel3 dynatb3 |label4 tb4  

The label 4 and its value is a static component and so needs to be pushed to the end.

I have searched a lot but i can't find HTML column creation at a specific location.

I have tried to insert the dynamic fields in the table using JS, but they don't generate at the desired position.

Here the code i have written

var table = document.getElementById("myTable");

 for(var i = 0; i < val ; i++){  
 // val is the number of td's needed

 var td1 = document.getElementById('td1');  // get id of tb3
 var text = document.createTextNode("some text"); 
 td1.appendChild(text);
 table.appendChild(td1);
 var newField = document.createElement('input');
 newField.setAttribute('type', 'text');
 var newTd = document.createElement('td');
 newTd.appendChild(newField);
 var newTr = document.createElement('tr');
 newTr.appendChild(newTd);
 table.appendChild(newTr);
 }

The above code generates the textboxes and the label "Some text", but not at the desired position. Can anyone please suggest how to go about solving this.

[edited]

$('<td>new cell</td>').insertAfter('table tr td:nth-child(3)')

[previous answer] You could always do it the dirty way...

$('<tr><td>one</td><td>two</td><td>three</td></tr>').insertAfter('table tr:nth-child(3)')

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