jquery – How to get the hidden values of a static column-ThrowExceptions

Exception or error:

I got a data grid view which has dynamic columns, it differs according to user inputs.
The columns are drawn according to date difference of the user.

<table class="table table-bordered" id="Tablev">
  <tr input type="hidden" id="trr">
   <th></th>
  </tr>
  <tr></tr>
</table>

I need to get all the hidden field values by using jquery and im using the the following to access it,but it shows an empty value.

var ask_id = $('#trr').val();
alert(ask_id);
How to solve:

As @barmar said <tr> elements don’t have a value. You HTML needs to be like below:

<table class="table table-bordered" id="Tablev">
    <tr><input type="hidden" id="trr" ></tr>
    <tr></tr>
</table>

Now you can do:

var ask_id = $('#trr').val();
alert(ask_id);

Working snippet:-

$(document).ready(function(){
   var ask_id = $('#trr').val();
   alert(ask_id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="Tablev">
  <tr><input type="hidden" id="trr" value="20"></tr>
  <tr></tr>
</table>

If multiple hidden elements are there and you want to grab values of all of them, then use loop and get the values in an array

var hiddenValues = [];

$('table').find('input:hidden').each(function(){

   hiddenValues.push($(this).val());
});
console.log(hiddenValues);

Working snippet:-

$(document).ready(function(){
    var hiddenValues = [];
    
    $('table').find('input:hidden').each(function(){
    
       hiddenValues.push($(this).val());
    });
    console.log(hiddenValues);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="Tablev">
  <tr><input type="hidden" id="trr" value="20"></tr>
  <tr>ABC</tr>
  <tr><input type="hidden" id="trr" value="10"></tr>
  <tr>DEF</tr>
</table>

Leave a Reply

Your email address will not be published. Required fields are marked *