I have a button at the bottom of my table. I have been messing around with java script, but Im confused on how I would add the correct amount of cells in each row upon clicking my button.
Also, is there a way to add a row, while it also adding a new set of buttons at the end of each row?
You can use the insertRow()
method, this creates an empty <tr>
element and adds it to a table. The insertRow()
method inserts the new row(s) at the specified index in the table. Note: A <tr>
element must contain one or more <th>
or <td>
elements.
function myFunction() { var table = document.getElementById("data-table"); var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = "NEW CELL1"; cell2.innerHTML = "NEW CELL2"; }
<!DOCTYPE html> <html> <head> <style> table, td { border: 1px solid black; } </style> </head> <body> <p>Click the button to add a new row at the first position of the table and then add cells and content.</p> <table id="myTable"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <br> <button onclick="myFunction()">Try it</button> </body> </html>
Here you have the information, this is what you need. http://www.w3schools.com/jsref/met_table_insertrow.asp
<a href="javascript:myFunction();" title="addRow" class="btn btn-info" id="row">Add Row</a>
<script>
function myFunction() {
var table = document.getElementById("data-table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(-1);
var cell4 = row.insertCell(-1);
var cell5 = row.insertCell(-1);
var cell6 = row.insertCell(-1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
cell4.innerHTML = "NEW CELL4";
cell5.innerHTML = "NEW CELL5";
cell6.innerHTML = "NEW CELL6";
}
</script>
I see you are using jQuery if you go in that way you could use something like:
$('#addRow').click(function(e){
e.preventDefault();
var $tr = $('<tr>').html("<td>cdcs</td><td>csc</td><td>cscs</td><td>cscs</td><td>cscs</td>");
var $tdButtons = $('<td>').html('<button>Compress</button><a href="#">Compress</a><a href="#">Download</a><a href="#">Delete</a>');
$tr.append($tdButtons);
$('#data-table').append($tr);
});
and the link add row must be something like
<a href='#' id="addRow">Add Row</a>
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.