mrdragon mrdragon - 5 months ago 10
HTML Question

how to get value of cell in table and display it in textbox

I have a table like this:

<table id="mytable">
<tr>
<th>Customer Id</th>
<th>Name</th>
</tr>
<tr>
<td>123</td>
<td>A</td>
</tr>
<tr>
<td>456</td>
<td>B</td>
</tr>
<tr>
<td>789</td>
<td>C</td>
</tr>
</table>
<form>
<input type="text" name="txtDsCode" id="txtDsCode"/>
</form>


When I click on the
textbox
and then click on the
cell
in the table , the value of the cell will display in the
textbox
.
How should i do it with javascript?
Thanks all!

Answer
  • Use querySelectorAll to select td elements
  • Use Array.from to cast array-like-object to array to apply array method
  • Register events using addEventListener

var cells = document.querySelectorAll('#mytable td');
Array.from(cells).forEach(function(elem) {
  elem.addEventListener('click', function() {
    document.getElementById('txtDsCode').value = this.textContent;
  })
})
<table id="mytable">
  <tr>
    <th>Customer Id</th>
    <th>Name</th>
  </tr>
  <tr>
    <td>123</td>
    <td>A</td>
  </tr>
  <tr>
    <td>456</td>
    <td>B</td>
  </tr>
  <tr>
    <td>789</td>
    <td>C</td>
  </tr>
</table>
<form>
  <input type="text" name="txtDsCode" id="txtDsCode" />
</form>