I made a web page with yii2, html and php. Now I have created a survey form. Each question contains multiple checkboxes. And now I want to check if there is at least one checkbox is checked for each question before submission. So how do I do it?
I have tried to use the jquery validation plugin and I think there is something wrong with my submit() function or the id for my checkboxes. Can somebody help?
The following are my codes:
'''
$number = 0;
foreach($questions as $question){
$count = $count + 1;
foreach($choices as $choice){
?>
<input id="testBox" type="checkbox" name="<?php echo 'q'.$count.'checkbox_ans[]'; ?>" value="<?php echo $choice->id; ?>"><?php echo $choice->getTitle(); ?>
<?php
}
}
?>
<?php
$this->registerJs('
var formHasChanged = false;
var submitted = false;
$(document).on("change", "form input", function (e) {
formHasChanged = true;
});
$("form").submit(function(event) {
$("#testForm").validate();
var is_valid = $("#testForm").valid();
var atLeastOneIsChecked = $("#testBox:checkbox:checked").length > 0;
if(is_valid && atLeastOneIsChecked){
submitted = true;
}
else{
event.preventDefault();
alert("please answer all questions.");
}
});
',
View::POS_END);
?>
'''