Reputation:
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
.
Upvotes: 1
Views: 3704
Reputation: 2675
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);
Upvotes: 3
Reputation: 5962
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 );
Upvotes: 0