Issue
I have an HTML page. On the page I have a table
with 8 columns and 56 rows and an input (number).
Whichever cell I click, I want it to transfer the number in it into the input
. How can I do that?
Thank you in advance for your help.
Solution
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!
Answered By - Jonathon Hibbard
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.