猿问

如何检查至少一个复选框被选中

我正在使用 PHP 和 HTML 制作调查表。我为每个问题制作了一个带有复选框的页面。现在我想检查每个问题是否至少选中了一个复选框(可以是多个)。


我试图为每个复选框放置“必需”属性,但是它要求用户在提交之前检查每个问题的所有复选框。我该怎么办?以下是我的代码:


<?php 

$number = 0;

foreach($questions as $question){

   $number = $number + 1;         

   foreach($choices as $choice){

?>


  <input type="checkbox" name="<?php echo 'q'.$number.'checkbox_ans[]'; ?>" value="<?php echo $choice->id; required ?>"><?php echo $choice->getTitle(); ?>


<?php    

    }

}

?>

它应该能够检测在提交之前是否至少为每个问题选中了一个复选框。


翻过高山走不出你
浏览 129回答 2
2回答

达令说

与.each(),.find()和.length。首先,在包含复选框的所有问题中放置一个常见的类,然后您可以循环使用每个问题和复选框:$('.question-container').each(function(index, element){&nbsp; &nbsp;// Then inside each container we search for the checkboxes&nbsp; &nbsp;var checked = $(element).find('input[type=checkbox]:checked');&nbsp; &nbsp;// Now we have the inputs that are checked, and we check how many&nbsp; &nbsp;if(checked.length){&nbsp; &nbsp; &nbsp;// Yes at least one checkbox is checked&nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp;// No, there are no checkbox checked for this question&nbsp; &nbsp;}})
随时随地看视频慕课网APP
我要回答