When using PHP to create web tables, you often need to use the function of adding rows. This article will introduce how to use PHP to add a row to the table when a button is clicked.
First, we prepare a table and set the initial number of rows. The specific code is as follows:
A button is added at the end of the table, used to trigger adding rows event. When the button is clicked, the
addRow()
function in JavaScript will be called.
function addRow() { // 获取当前表格行数 var rowCount = document.getElementById("myTable").rows.length; // 创建一行新的 table row 元素 var row = document.createElement("tr"); // 遍历表格头 for (var i = 0; i < 3; i++) { // 创建新的 table cell 元素 var cell = document.createElement("td"); // 每列的内容 var column = ""; if (i == 0) { // 序号列 column = rowCount; } else { // 输入框列 column = ''; } // 插入新的内容到 cell 元素 cell.innerHTML = column; // 插入 cell 元素到 row 元素 row.appendChild(cell); } // 插入新的 row 元素到 table 元素的 tbody 子元素 document.getElementById("myTable").getElementsByTagName('tbody')[0].appendChild(row); }
In this method, first get the current number of rows in the table through It should be noted that when creating a new input box, the name needs to be set to a different value. Here, the line number is used as the suffix. The specific code is as follows: This way you can achieve When the button is clicked, the effect of table rows is dynamically added. Summary The method of dynamically adding table rows in PHP is not complicated and can be achieved with the help of JavaScript. Through the introduction of this article, I believe that readers have mastered the method of adding table rows after clicking a button. The above is the detailed content of How to add a row to the table by clicking a button in php. For more information, please follow other related articles on the PHP Chinese website!document.getElementById("myTable").rows.length
. Then, usedocument.createElement("tr")
to create a newelement, and use document.createElement("td")
to create it in a loop Three newelements and insert new content. Finally, use document.getElementById("myTable").getElementsByTagName('tbody')[0].appendChild(row)
to insert the new row element into the table'sin child elements.
column = '';