我有问题要显示All Checked框从一种形式显示到另一种形式,并带有“,”分隔。
目前,下面的脚本正在努力只显示一个复选框
<html>
<body>
<form id="form1">
<input name="items[]" id="item1" type="checkbox" value="item1" checked>
<input name="items[]" id="item2" type="checkbox" value="item2">
<input name="items[]" id="item3" type="checkbox" value="item3">
<input type="button" border="2" onClick="checkedBox();" >
</form>
<form id="form2">
<p id="view" id="view">Display Here</p>
</form>
<script>
function checkedBox() {
var input = document.querySelector('input[name="items[]"]:checked').value;
document.getElementById("view").innerHTML = input;
}
</script>
</body>
</html>
请协助我显示所有复选框,例如:如果选择了第1项和第2项,则应视为“item1,item2”
答案 0 :(得分:0)
function checkedBox() {
var a= document.querySelectorAll('input:checked');
var b= [].slice.call(a);
var c="";
b.forEach(function(a){
c += a.value+",";
})
document.getElementById("view").innerHTML=c.slice(0, -1);;
}
&#13;
<html>
<body>
<form id="form1">
<input name="items[]" id="item1" type="checkbox" value="item1" checked>
<input name="items[]" id="item2" type="checkbox" value="item2">
<input name="items[]" id="item3" type="checkbox" value="item3">
<input type="button" border="2" onClick="checkedBox();" >
</form>
<form id="form2">
<p id="view" id="view">Display Here</p>
</form>
</body>
</html>
&#13;
答案 1 :(得分:0)
使用querySelectorAll而不是querySelector然后遍历每个元素并获取其值
试试这个:
function checkedBox() {
document.getElementById("view").innerHTML = "";
var input = document.querySelectorAll('input[name="items[]"]:checked');
for (i = 0; i < input.length; i++) {
document.getElementById("view").innerHTML += input[i].value;
if(i!=(input.length-1)) {
document.getElementById("view").innerHTML += ",";
}
}
}
<form id="form1">
<input name="items[]" id="item1" type="checkbox" value="item1" checked>
<input name="items[]" id="item2" type="checkbox" value="item2">
<input name="items[]" id="item3" type="checkbox" value="item3">
<input type="button" border="2" onClick="checkedBox();">
</form>
<form id="form2">
<p id="view" id="view">Display Here</p>
</form>
答案 2 :(得分:0)
<script>
function checkedBox() {
var input = document.querySelector('input[name="items[]"]:checked');
for (i = 0; i < input.length; i++) {
document.getElementById("view").innerHTML += input[i].value + ",";
}
}
</script>
答案 3 :(得分:0)
function checkedBox() {
let input = document.querySelectorAll('input[name="items[]"]:checked');
let countInput = input.length;
let inputValues = []
if(countInput > 0){
for(let i =0; i < countInput; i++){
inputValues.push(input[i].value);
}
document.getElementById("view").innerHTML = inputValues.join(',');
} else {
document.getElementById("view").innerHTML = '';
}
}