2

I am making a survey form with PHP and HTML. I have made a page with checkboxes for each question. Now I want to check whether at least one checkbox is checked (it can be multiple) for each question.

I have tried to put the 'required' attributes for each checkbox, but then it required user to check all the checkboxes for each question before submission. What should I do? The following are my codes:

<?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    
    }
}
?>

It should be able to detect whether at least one checkbox is checked for each question before submission.

Web Worker
  • 41
  • 1
  • 4

2 Answers2

-1

With .each(), .find() and .length.

First of all, put a class that is common in all your questions that contain the checkboxes, then you can loop the questions and check checkboxes for each with:

$('.question-container').each(function(index, element){
   // Then inside each container we search for the checkboxes
   var checked = $(element).find('input[type=checkbox]:checked');
   // Now we have the inputs that are checked, and we check how many
   if(checked.length){
     // Yes at least one checkbox is checked
   } else {
     // No, there are no checkbox checked for this question
   }
})

Check if checkbox is checked with jQuery

Josep Vidal
  • 2,580
  • 2
  • 16
  • 27
-1

Try this hope it helps .Use is(':checked') to find if check box is checked or not

$('.check').click(function(e){

var status=0

$('.item_check').each(function(e){
     
          if($(this).is(':checked'))
          status=1
})

if(!status)
console.log('no items checked')

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="item_check">1
<input type="checkbox" class="item_check">2
<input type="checkbox" class="item_check">3
<input type="checkbox" class="item_check">4
<button class="check">Check</button>
Deepak A
  • 1,624
  • 1
  • 7
  • 16
  • 1
    This is not what the question asked, it requires to validate multiple checkboxes across diferents divs, your case is only for a simple checkbox input, not for validating multiples inside diferents divs. – Josep Vidal Jul 17 '19 at 07:52