0

I have a table with dynamic rows that each rows contain an input alongside of its button(in the third cell).

The code below represents one row of my table:

window.getKey = function(ele) {

  var row = ele.closest('tr');

  console.log("cell 0: " + row.cells[0].textContent);
  console.log("cell 1: " + row.cells[1].textContent);
  console.log("cell 2: " + row.cells[2].children[0].value);
}
<table class="table table-striped table-bordered text-center table-hover" id="tbl_posts">
  <tr class="satr">
    <th class="colu">Username</th>
    <th class="colu">Post</th>
    <th class="colu">Decode</th>
  </tr>
  <tr>
    <td>
      <p>Mike</p>
    </td>
    <td>
      <p>Content</p>
      <td>
        <div>
          <input id="key_input" type="number" placeholder="Enter number" />
          <div>
            <button class="btn btn-outline-secondary" id="decode" type="submit" onclick="getKey(this)">Decode</button>
          </div>
        </div>
      </td>

As you see the console.log() shows the content of cells except the third cell. The other questions did not help me (like: How to retrieve value of input type in a dynamic table)

How can I access the input value in the third cell?

Hossein Asmand
  • 109
  • 1
  • 9

1 Answers1

2

Based on your HTML code, row.cells[2].children[0].value gets the value of the div, not the input. To get the value of the input, you can use:

  • row.cells[2].children[0].children[0].value or
  • row.cells[2].querySelector("input").value.

Code:

window.getKey = function(ele) {
  var row = ele.closest('tr');

  console.log("cell 0: " + row.cells[0].textContent);
  console.log("cell 1: " + row.cells[1].textContent);
  console.log("cell 2: " + row.cells[2].querySelector("input").value);
}
<table class="table table-striped table-bordered text-center table-hover" id="tbl_posts">
  <tr class="satr">
    <th class="colu">Username</th>
    <th class="colu">Post</th>
    <th class="colu">Decode</th>
  </tr>
  <tr>
    <td>
      <p>Mike</p>
    </td>
    <td>
      <p>Content</p>
    </td>
    <td>
      <div>
        <input id="key_input" type="number" placeholder="Enter number" />
        <div>
          <button class="btn btn-outline-secondary" id="decode" type="submit"
              onclick="getKey(this)">Decode</button>
        </div>
      </div>
    </td>
  </tr>
</table>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66