[Answered ]-How can I populate a form field from a list of elements in JavaScript?

1๐Ÿ‘

โœ…

If you have that value as data-attribute inside your button you can simply use this.getAttribute("attrname") or else use el.closest("tr").children[0].textContent where children[0] represent first td .

Demo Code :

function selectPlayer(el) {
  document.getElementById("QB_name").value = el.getAttribute("data-player-name")
  //or 
  console.log(el.closest("tr").children[0].textContent.trim())
  //or
  console.log(el.closest("tr").querySelector(".qbname").textContent.trim())
}
<table>
  <tbody id="page1">

    <tr>
      <td>
        <h6 class="qbname">abc</h6>
      </td>
      <!--pass this-->
      <td><button onclick="selectPlayer(this)" type="button" id="qbackbutton" class="btn btn-success btn-sm m-0 waves-effect" data-player-name="abs" data-position="{{ q.position }}">Add</button></td>
      <td>
        <h6> {{ q.team }} </h6>
      </td>
      <td>
        <h6> {{ q.position }} </h6>
      </td>
      <td>
        <h6>{{ q.points }}</h6>
      </td>
    </tr>
    <tr>
      <td>
        <h6 class="qbname">abc2</h6>
      </td>
      <!--pass this-->
      <td><button onclick="selectPlayer(this)" type="button" id="qbackbutton" class="btn btn-success btn-sm m-0 waves-effect" data-player-name="abs2" data-position="{{ q.position }}">Add</button></td>
      <td>
        <h6> {{ q.team }} </h6>
      </td>
      <td>
        <h6> {{ q.position }} </h6>
      </td>
      <td>
        <h6>{{ q.points }}</h6>
      </td>
    </tr>

  </tbody>
</table>
<input type="text" id="QB_name">
๐Ÿ‘คSwati

Leave a comment