我在验证多个复选框时遇到问题,我想检查用户是否至少选择了一个复选框。 我尝试使用 document.getElementByClassName 但不起作用
HTML:
<form id="formupload" method="post" enctype="multipart/form-data" action="upload.php" name="formupload">
<input onKeydown="javascript:validateForm();" id="txtFileName" name="txtFileName" />
<input onKeydown="javascript:validateForm();" id="title" name="title" />
<input onKeydown="javascript:validateForm();" id="keywords" name="keywords" />
<input onKeydown="javascript:validateForm();" id="description" name="description" />
<span class="niche">
<input type="checkbox" value="1" name="channel[]" class="css-checkbox" id="box_1">
<label class="css-label" name="lbl_1" for="box_1">Amateur</label>
</span>
<span class="niche">
<input type="checkbox" value="2" name="channel[]" class="css-checkbox" id="box_2">
<label class="css-label" name="lbl_2" for="box_2">Amateur</label>
</span>
<span class="niche">
<input type="checkbox" value="3" name="channel[]" class="css-checkbox" id="box_3">
<label class="css-label" name="lbl_3" for="box_3">Amateur</label>
</span>
<button id="btnSubmit" class="btn lbtn upBtn" type="submit">Upload</button>
</form>
这是 JavaScript:
function validateForm() {
var txtFileName = document.getElementById("txtFileName");
var titleTxt = document.getElementById("title");
var tagsTxt = document.getElementById("keywords");
var descTxt = document.getElementById("description");
var isValid = true;
if (txtFileName.value === "" || titleTxt.value === "" || tagsTxt.value === "" || descTxt.value === "" ) {
isValid = false;
}
document.getElementById("btnSubmit").disabled = !isValid;
}
最佳答案
var checkBoxes=document.getElementsByClassName("css-checkbox");
var booleanResult=false;
for(var i=0;i<checkBoxes.length;i++){
if(checkBoxes[i].checked){
booleanResult=true;
break;
}
}
if(booleanResult==false){
alert("invalid")
}
<强> DEMO
关于javascript - 使用 javascript 验证复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16653915/