0

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);
 ?>

'''

Tom
  • 39
  • 1
  • if you are using jquery validate: https://stackoverflow.com/questions/19714318/jquery-validate-at-least-one-from-a-group-of-checkboxes-is-checked-only-if-a-r – Pete Jul 19 '19 at 09:32
  • Possible duplicate of [Yii2 : validate if at least one checkbox is selected](https://stackoverflow.com/questions/41209265/yii2-validate-if-at-least-one-checkbox-is-selected) – Muhammad Omer Aslam Jul 19 '19 at 09:48

0 Answers0