0

I have this html table and 2 textboxes:

<table id="myTbl">
   <thead>
     <tr>
       <th>A</th>
       <th>B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
 </tbody>
</table>
<input type="text" name="txt" id="txt" >
<input type="text" name="txt" id="txt2" >

I want when reload the page, the values 1 and 2 must display in each textbox. How can I do it?

I have tried this js code but wrong and I want it auto display, not to click it:

var cells = document.querySelectorAll('#myTbl tbody ');
    Array.from(cells).forEach(function (elem) {
      elem.addEventListener('click', function () {
        document.getElementById('txt').value = this.textContent;
      })
    })
ttt
  • 29
  • 5
  • What have you tried and where do you get stuck? You might find [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) useful. – showdev Sep 30 '22 at 01:59
  • Are you looking for just a static default value or a dynamic default value? – Alvin Sep 30 '22 at 02:01
  • @showdev Thanks, I edited to show what I've tried. – ttt Sep 30 '22 at 02:12
  • For static it is just add `value` to your input like that ``. To make it dynamic, you might need to use more complex solutions so maybe it is one step at the time – Alvin Sep 30 '22 at 02:15
  • @showdev oh my bad, its dynamic. I edited the js code above, can you look for it? – ttt Sep 30 '22 at 02:20
  • Here are some [examples of how to use local storage](https://stackoverflow.com/questions/17087636/how-to-save-data-from-a-form-with-html5-local-storage) to make form values persist after reloading the page. They might be useful for you. – showdev Oct 01 '22 at 03:24

1 Answers1

0
var tbody = document.getElementsByTagName('tbody')[0]
var input1 = document.getElementById('txt')
var input2 = document.getElementById('txt2')

input1.value = tbody.getElementsByTagName('td')[0].textContent
input2.value = tbody.getElementsByTagName('td')[1].textContent

Darko Riđić
  • 459
  • 3
  • 18