我试图使至少一个复选框处于活动状态,如果最后一个复选框处于活动状态,则按钮被激活,但是第一个复选框处于活动状态时,该按钮处于不活动状态
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>
最佳答案
我已经修复了您的代码,尽管您可以通过多种方法来实现它。 :)
function chose(){
var txt="";
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var flag = false;
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked){
flag = true;
document.getElementById("btn").disabled = false;
txt = txt + checkboxes[i].value + " ";
}
}
if(!flag){
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()">
<span id="result"> </span>
</form>