[英]How to add new row in table from user input in HTML
我只想建立一個網站。 它有一個表,顯示每行的數據。 基本上,當用戶單擊添加按鈕時,此表必須能夠添加包含新數據的新行。
這是我的代碼:
function myFunction() { var table = document.getElementById("myTable"); var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = "NEW CELL1"; cell2.innerHTML = "NEW CELL2"; }
table, td { border: 1px solid black; }
<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>
但是該代碼的結果是,當用戶單擊添加按鈕時,它始終顯示“ NEW CELL 1”和“ NEW CELL 2”。 我的問題是,如何修改代碼,尤其是:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
這樣,該表就可以從用戶那里獲取輸入數據了?
只需獲取您的輸入值並將其設置為目標單元格的html值
function myFunction() { var table = document.getElementById("myTable"); var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = document.getElementById('cellOne').value; cell2.innerHTML = document.getElementById('cellTwo').value; }
table, td { border: 1px solid black; }
<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> <input type='text' id='cellOne' /> <input type='text' id='cellTwo' /> <button onclick="myFunction()">Try it</button>
您需要一些表單輸入來輸入文本,這是一個非常基本的示例,可以幫助您入門:
function myFunction() { var table = document.getElementById("myTable"); var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = document.querySelector('#newCellOneText').value; cell2.innerHTML = document.querySelector('#newCellTwoText').value; }
table, td { border: 1px solid black; }
<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> Cell 1 Text: <input type="text" id="newCellOneText" /><br/> Cell 2 Text: <input type="text" id="newCellTwoText" /><br/> <button onclick="myFunction()">Try it</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.