How to add a row to the table by clicking a button in php

PHPz
Release: 2023-03-31 09:45:08
Original
845 people have browsed it

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:

   PHP 点击按钮表格增加一行  
'; echo ''; echo ''; echo ''; echo ''; } ?>
编号 姓名 年龄
'.$i.'

Copy after login

A button is added at the end of the table, used to trigger adding rows event. When the button is clicked, theaddRow()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); }
Copy after login

In this method, first get the current number of rows in the table throughdocument.getElementById("myTable").rows.length. Then, usedocument.createElement("tr")to create a newelement, and usedocument.createElement("td")to create it in a loop Three newelements and insert new content. Finally, usedocument.getElementById("myTable").getElementsByTagName('tbody')[0].appendChild(row)to insert the new row element into the table'sin child elements.

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:

column = '';
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!