1

I am beginner webdeveloper; I make my project in Html/Css/jQuery.

I have 5 checkboxes on the website. 3 of them have the checkboxRequired class. After clicking on each of the 5 checkboxes, I have to check if all 3 checkboxes with the checkboxRequired checkout are selected.

I try this solution:

$('input[type="checkbox"]').click(function(){
    if($('input:checkbox.checkboxRequired').prop('checked')){
        console.log("Checkbox is checked.");
    }
    else {
        console.log("Checkbox is unchecked.");
    }
});

but it's always show: Checkbox is unchecked.

How can I repair it?

Please help me.

trzew
  • 385
  • 1
  • 4
  • 13

4 Answers4

2

You need to use the .is() method and the :checked selector.

On clicking of a checkbox - you iterate over the checkboxes with the required class (using the .each() method) and can test each to see if its checked or not.

Note the little ternary equation in there to demonstrate an alternative to the traditional if/ else block - but it does the same thing (the "?" line is equivalent to true and the ":" is equivalent to false / else....

EDIT - I have updated the function to match your needs. Basically you need to check if all the checkboxes are checked and if so - submit the form and if not - raise the error modal.

The following amended code should do that for you.

$('input[type="checkbox"]').click(function(){

let total = 0;
let checked = 0;

  $('.checkboxRequired').each(function(index){
    total += 1;
    if( $(this).is(':checked') ) {checked +=1 }
  })
  
  total === checked 
    ? ($('.orderForm').submit(), console.log('Form Submitted'))
    : $('#errorModal').modal('show');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>


<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 1</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 2</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 3</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 4</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 5</label>

<!-- form
<form class="orderForm"  method="post"></form>
-->

<!-- Modal -->
<div id="errorModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Error Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>There is a disturbance in the force..... not all required checkboxes are checked</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
  • Thank you. When I want send- when all required checkbox was checked then this code is correct: if($(this).is(':checked')){ $('.orderForm').submit(); } else { $('#errorModal').modal('show'); }? I have error: jquery-3.5.1.min.js:2 Uncaught RangeError: Maximum call stack size exceeded – trzew Aug 18 '20 at 09:26
1

You can check the checked status in the element itself. Like this:

$('input[type="checkbox"]').click(function(){
    if($('input:checkbox.checkboxRequired')[0].checked){
        console.log("Checkbox is checked.");
    }
    else {
        console.log("Checkbox is unchecked.");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxRequired">
Wimanicesir
  • 4,606
  • 2
  • 11
  • 30
0

I would try to check if all 3 checkboxes with the .checkboxRequired are selected in this way:

$('input[type="checkbox"]').click(function(){
  const checkboxes = $('.checkboxRequired:checked');
  
  if (checkboxes.length === 3) {
    console.log("All 3 required checkboxes are checked.");
  } else {
    console.log("Some required checkbox is unchecked.");
  }
});

Demo - https://codepen.io/vyspiansky/pen/NWNrLXN

Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11
0

Because $('input:checkbox.checkboxRequired') is select all elements by that selector. But prop method works with first element only:

Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

Link to docs: https://api.jquery.com/prop/

Depending on your needs, you can handle it in other ways:

  1. Simplest way: you can use attribute required - see docs
  2. If you need more custom way, you can do something like that:
var $form2 = $('form#action2')
$form2.submit(function(e){
    var isAllReqChecked = true
    $form2.find('input:checkbox.checkboxRequired')
        .each(function propChecker(){
          isAllReqChecked &= $(this).prop('checked')
        })
  alert(isAllReqChecked ? 'All required was checked!' : 'Not all required was checked')
  e.preventDefault()
});

Check demo

Gormonn
  • 31
  • 5