JQuery each getting value of multiple table data in a table row

邮差的信 提交于 2020-02-08 05:22:06

问题


Hi there I have this table which has multiple rows. I want to know how to get certain data in each row of this table. In this table I needed to get the student number data and it's accompanying grade.

<tbody>
   <?php foreach ($class_list_view as $student) { ?>
   <tr>
      <td class="studentnumber"><?= $student->studentnumber ?></td>
      <td><?= $student->lastname ?></td>
      <td><?= $student->firstname ?></td>
      <td><?= $student->middlename ?></td>
      <td><?= $student->level ?></td>
      <td><?= $student->year ?></td>
      <td>
         <select class="custom-select grade" style="height: 20px;">
            <option selected value="">Select Grade</option>
            <option value="passed">Passed</option>
            <option value="failed">Failed</option>
         </select>
      </td>
   </tr>
   <?php } ?>
</tbody>

What I have tried is using the each loop in jquery but I don't know how get similar/inline selectors with it.

 $("table tbody tr td.studentnumber").each(function (index) {
        studentnum_array.push( {"studentnumber": $(this).text(), "grade": $('table tbody tr td select.grade').val() } );
    });

     console.log( studentnum_array );

But in the grade index it only takes the first one. It should take in the value of the select in each row similar to the td studentnumber.


回答1:


You can loop through the rows instead of the cells...

var studentnum_array = [];

$("table tbody tr").each(function(index) {
    studentnum_array.push({ 
        "studentnumber": $(this).find('td.studentnumber').text(),
        "grade": $(this).find('select.grade').val()
    });
});

console.log(studentnum_array);

If you want to loop through the cells, you have to find the select in relation to the corresponding studentnumber cell...

var studentnum_array = [];

$("table tbody td.studentnumber").each(function(index) {
    studentnum_array.push({ 
        "studentnumber": $(this).text(),
        "grade": $(this).closest('tr').find('select.grade').val()
    });
});

console.log(studentnum_array);



回答2:


As you are already looping through each td then you need to find it's enclosing tr then find select.

 $("table tbody tr td.studentnumber").each(function (index) {
            var grade = $(this).closest('tr').find('select.grade').val();
            studentnum_array.push( {"studentnumber": $(this).text(), "grade": grade } );
        });

         console.log( studentnum_array );


来源:https://stackoverflow.com/questions/46725579/jquery-each-getting-value-of-multiple-table-data-in-a-table-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!