我正在尝试显示此表单中的所有选中的复选框。
<form name="myform">
Select a check box: <br> <br>
Check Box 0: <input TYPE="checkbox" NAME="checkBox" checked> <br>
Check Box 1: <input TYPE="checkbox" NAME="checkBox"> <br>
Check Box 2: <input TYPE="checkbox" NAME="checkBox"> <br>
Check Box 3: <input TYPE="checkbox" NAME="checkBox"> <br> <br>
<input type="button" name="button" Value="Click Me" onClick="getCheckedBoxes(this.form)">
</form>
这是JS代码。我现在被困在这里,无法让它发挥作用。提前谢谢。
function getCheckedBoxes(checkBox) {
var checkboxes = document.getElementsByName(checkBox);
var checkboxesChecked = [];
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
var checkedBoxes = getCheckedBoxes("checkBox");
alert ("Check box " + checkedBoxes + " is selected ");
答案 0 :(得分:1)
您需要在调用onclick的函数内部进行警报,并且需要存储索引而不是对象。如果存储对象,则会发出警告
Check box: [object HTMLInputElement],[object HTMLInputElement] is selected
而不是索引。
function getCheckedBoxes(boxName) {
var checkboxes = document.getElementsByName(boxName);
var checkboxesChecked = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(i); // or i+1 if you want 1-based
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : "none";
}
function count(name) {
alert("Checked boxes: " + getCheckedBoxes(name));
}
<form name="myform">
Select a check box: <br> <br> Check Box 0: <input TYPE="checkbox" NAME="checkBox" checked> <br> Check Box 1: <input TYPE="checkbox" NAME="checkBox"> <br> Check Box 2: <input TYPE="checkbox" NAME="checkBox"> <br> Check Box 3: <input TYPE="checkbox" NAME="checkBox"> <br> <br>
<input type="button" name="button" Value="Click Me" onClick="count('checkBox')">
</form>
使用
更新我需要更新HTML以在复选框上显示ID或读取标签内容
function getCheckedBoxes(boxName) {
var checkedBoxes = document.querySelectorAll("[name="+boxName+"]:checked");
var ids = [...checkedBoxes].map(x => x.id)
return ids.length===0?"":ids.join(", ");
}
document.getElementById("button").addEventListener("click",function() {
console.log(
getCheckedBoxes(this.getAttribute("data-name"))
)
});
<form name="myform">
Select a check box:<br/>
<label>Check Box 0: <input id="chk0" TYPE="checkbox" NAME="checkBox" checked /></label><br/>
<label>Check Box 1: <input id="chk1" TYPE="checkbox" NAME="checkBox" /></label><br/>
<label>Check Box 2: <input id="chk2" TYPE="checkbox" NAME="checkBox" /></label><br/>
<label>Check Box 3: <input id="chk3" TYPE="checkbox" NAME="checkBox" /></label><br/>
<input type="button" id="button" value="Click Me" data-name="checkBox" />
</form>