Skip to content
Advertisement

How can I pass a hidden html element`s value to jQuery?

I have a hidden element with a PHP dynamic value in HTML and I would like to get it in jQuery when I click in a row of the table where the value is. Right now I can click on a row and get the value of the first column of that row but it prints the entire element as a string.

<td>
  <input type="hidden" name="zyx" value="test id" />
</td>

jquery code:

$(document).ready(function() {
        var table = $('#myTable').DataTable();
        $('#myTable tbody').on('click', 'tr', function() {
            var data = table.row(this).data();
            alert(data[0]);      
        });
    });

this is what it prints: “<input type="hidden" name="zyx" value="test id">

Advertisement

Answer

You can simply use .find to find the first input inside the first td found inside the clicked row:

$(document).ready(function() {
  $('#myTable tbody').on('click', 'tr', function() {
    const $input = $(this).find('td:first-child input');
    console.log($input.val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
    <tbody>
      <tr><td><input type="hidden" name="xyz" value="value 1" />Value 1</td></tr>
      <tr><td><input type="hidden" name="wxy" value="value 2" />Value 2</td></tr>
    </tbody>
</table>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement