我有一张桌子,每行都有一个复选框。
选中复选框后,我想调用JavaScript函数。我想知道这是如何工作的,例如,如果我单击表格第二行的复选框,它会调用一个javascript函数并将一个类应用于td标记。
这是我的表...
while ($row = $result->fetch_object()) {
echo "<tr id='request-$row->ar_Id'>";
echo "<td id='request-checked'><input type='checkbox' id='chk-appRequest' onchange='flagRequestAsSelected()'></span></td>";
echo '<td>' . $row->ar_Id . '</td>';
echo '<td>' . $row->ar_patientId . '</td>';
echo '<td>' . $row->pd_forename . ' ' . $row->pd_lastname . '</td>';
echo '<td>' . $row->ar_appointmentTime . '</td>';
echo '<td id="requestedDate">' . $row->ar_appointmentDate . '</td>';
echo '<td>' . $row->ar_doctorId . '</td>';
echo '<td id="alternativeAptTime" aria-hidden="true">' . $row->ar_alternativeTime . '</td>';
echo '<td id="alternativeAptDate" aria-hidden="true">' . $row->ar_alternativeDate . '</td>';
echo '<td id="alternativeAptDoctor" aria-hidden="true">' . $row->ar_alternativeDoctor . '</td>';
echo '<td id="bookedBit" aria-hidden="true">' . $row->ar_booked . '</td>';
echo '</tr>';
}
JavaScript -
function flagRequestAsSelected()
{
var table = document.getElementById("tbl-appointment-requests");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
'How to check if checkbox is checked???
if (.checked == true)
{
col.innerHTML = "BLAH";
}
}
}
}
答案 0 :(得分:1)
您只需编辑您的问题,希望我的新答案能为您提供帮助。
所以改变你的html
<input type='checkbox' id='chk-appRequest' onchange='flagRequestAsSelected(this)'>
<!-- I added (this) inside your function parameters list -->
编辑你的JS
function flagRequestAsSelected(obj){ // I added obj param
var table = document.getElementById("tbl-appointment-requests");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
//How to check if checkbox is checked???
if (obj.checked == true){ // Check if the returned object is checked
col.innerHTML = "BLAH";
}
}
}
}
老答案:
使用jQuery,你可以做到这一点
$(".myInputClass").on("change", function() {
console.log("this change!");
if($(this).is(':checked')) {
$(this).parent().addClass("myClass"); // Add class to the td parent
}
}