Reputation: 254
I just want to build a website. It has a table, that shows data of each row. Basically, this table must be able to add new rows that contain new data, when user click add button.
This is my code:
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>
But the result of that code is, when user click add button, it always show "NEW CELL 1" and "NEW CELL 2". My question is, how to modify the code, especially:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
So that, the table is possible to get input data from user?
Upvotes: 0
Views: 3379
Reputation: 6780
You need some form inputs to allow you to enter text, here is a very basic example to get you started:
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>
Upvotes: 3
Reputation: 4014
Simply take your input value and set it as the html value for the target cells
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>
Upvotes: 4