gpt4 book ai didi

javascript - 如果至少选中一个复选框,则应启用按钮

转载 作者:行者123 更新时间:2023-11-30 19:12:48 24 4
gpt4 key购买 nike

如果至少选择了一个复选框,我试图使按钮处于事件状态,如果选择了最后一个复选框,按钮将被激活,但是当选择第一个复选框时,它处于非事件状态

 function chose(){
var txt="";
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
console.log(checkboxes);
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked){
document.getElementById("btn").disabled = false;
txt = txt + checkboxes[i].value + " ";
}
else{
document.getElementById("btn").disabled = true;
}
}
var result=document.getElementById("result");
result.innerHTML=txt;
}
<form action="" method="GET">
<label for="user">Name</label>
<input type="text" name="username" id="user" value="" placeholder="Input name">
<input type="button" name="" value="Send" id="btn" disabled="true" onclick="chose()">
IceCream:<input type="checkbox" name="one" id="param_1" value="IceCream" onchange="chose()">
Chocolate:<input type="checkbox" name="one" id="param_2" value="Chocolate" onchange="chose()">

</form>

最佳答案

使用 :checked

function chose() {
var checked = document.querySelectorAll('input[name="one"]:checked');
document.getElementById('btn').disabled = !checked.length;

var text = Array.from(checked).reduce(function(res, cb) {
return res + cb.value + ' ';
}, '');
document.getElementById('result').innerHTML = text;
}
<form action="" method="GET">
<label for="user">Name</label>
<input type="text" name="username" id="user" value="" placeholder="Input name">
<input type="button" name="" value="Send" id="btn" disabled="true" onclick="chose()"> IceCream:
<input type="checkbox" name="one" id="param_1" value="IceCream" onchange="chose()"> Chocolate:
<input type="checkbox" name="one" id="param_2" value="Chocolate" onchange="chose()">
</form>

<div id="result"></div>

关于javascript - 如果至少选中一个复选框,则应启用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58304313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com