我有一个具有相同类的复选框,基本上它的作用是,如果我选中该复选框,它将检查与该复选框相同的类,并且它将返回值。但它不会直接返回,我需要单击某处然后将其注册到文本框。我需要的是当我选中复选框时将直接值输入到文本框中。表代码来自 php,因此类+编号会发生变化,并且无法修复。
下面是它的片段。
function doSomethingElse(row) {
//select all checkboxes with name userid that are checked
var checkboxes =
document.querySelectorAll("input[name='student_name[]']:checked")
var values = "";
//append values of each checkbox into a variable (seperated by commas)
for (var i = 0; i < checkboxes.length; i++) {
values += checkboxes[i]
.value + ","
}
//remove last comma
values = values.slice(0, values.length - 1)
//set the value of input box
document.getElementById("stud_name").value = values;
}
$("input:checkbox").change(function() {
//alert('Ok!');
var value = $(this).attr("class");
$(":checkbox[class='" + value + "']").prop("checked", this.checked);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr onclick="doSomethingElse(this);">
<td><input type="checkbox" class="something1" name="user_id[]" value='' /></td>
<td><input type="checkbox" class="something1" name="student_name[]" value='1' /></td>
<td><input type="checkbox" class="something2" name="student_name[]" value='' /></td>
<td><input type="checkbox" class="something2" name="user_id[]" value='2' /></td>
</tr>
</table>
<input class="form-control" name="stud_name" id="stud_name" type="text" maxlength="255" />
最佳答案
尝试使用 $("input:checkbox").click(function () {
而不是 change
function doSomethingElse(row){
//select all checkboxes with name userid that are checked
var checkboxes = document.querySelectorAll("input[name='student_name[]']:checked")
var values = "";
//append values of each checkbox into a variable (seperated by commas)
for(var i=0;i<checkboxes.length;i++){
values += checkboxes[i].value + ","
}
//remove last comma
values = values.slice(0,values.length-1);
//set the value of input box
document.getElementById("stud_name").value = values;
}
$("input:checkbox").click(function () {
//alert('Ok!');
var value = $(this).attr("class");
$(":checkbox[class='" + value + "']").prop("checked", this.checked);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr onclick="doSomethingElse(this);">
<td><input type="checkbox" class ="something1"name="user_id[]" value='ID1' /></td>
<td><input type="checkbox" class ="something1"name="student_name[]" value='NAME1' /></td>
<td><input type="checkbox" class ="something2"name="student_name[]" value='NAME2' /></td>
<td><input type="checkbox" class ="something2"name="user_id[]" value='ID2' /></td>
</tr>
</table>
<input class="form-control" name="stud_name" id="stud_name" type="text" maxlength="255" />
关于javascript - 当我选中一个复选框(同一类)并将值插入文本框时,如何选中另一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55965976/