[Solved] JavaScript pull data from HTML table cell to input [closed]


const myInput = document.querySelector('#myInput');
const cells = document.querySelectorAll('#myTable tr td');

cells.forEach(el => 
    el.addEventListener('click', (e) => myInput.value = e.currentTarget.innerText)
);

This is assuming html like the following:

<input type="text" id="myInput" value="" />
<table id="myTable">
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
</table>

Update (Breakdown of what we are doing above):

All we are doing is we are keeping things really simple. We create a selector for the elements we’re after. Given there are multiple table cells, we use querySelectorAll which will return an array of elements.

We then just loop over all these elements and add a click event listener to each of them. The listener grabs the innerText of the cell and just sets it to the targeted input box.

This could be expanded on however you want. Chose to keep this simple and just do what was being asked.

Hope that helps!

3

solved JavaScript pull data from HTML table cell to input [closed]