简体   繁体   中英

How can I set a hidden input value by class in a table

I have this table structure.

<table id="my_table">
 <tr class="odd" id="row_1">
  <td></td>
  <td><input type="hidden" id="flight_1" value=""></td>
 </tr>
 <tr class="odd" id="row_2">
  <td></td>
  <td><input type="hidden" id="flight_2" value=""></td>
 </tr>
 <tr class="odd" id="row_3">
  <td></td>
  <td><input type="hidden" id="flight_3" value=""></td>
 </tr>
 <tr class="even" id="row_4">
  <td></td>
  <td><input type="hidden" id="flight_4" value=""></td>
 </tr>
 <tr class="even" id="row_5">
 <td></td>
  <td><input type="hidden" id="flight_5" value=""></td>
 </tr>
 <tr class="even" id="row_6">
  <td></td>
  <td><input type="hidden" id="flight_6" value=""></td>
 </tr>

How can I set the value of the hidden value for each row based on the class of the tr tags. For instance I have 9 row in the table with class 'odd' for 3 rows, 'even' for the next 3 rows and 'odd' for the last 3 rows. This can be dynamic, as in I could have 5 classes of rows alternating back and forth in the table creating 7 rows with class 'even', 7 rows with class 'odd' and back to 'even' etc. What I need to do is set the hidden values for each class to end up being '1' for the first 'odd' class and then '2' for the next 'even' class etc. I have tried to no avail using jquery. My jquery skills are pretty limited. Is this possible using jquery or is there another solutuion?

Check if the current class equals the previous class, and increment a counter

var i = 0;

$('#my_table tr').each(function() {
    if ( this.className != ($(this).prev().length ? $(this).prev().get(0).className : '')) i++;
    $(this).find('input').val(i);
});

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM