javascriptjquerycheckbox

Block form submit if no one checkbox checked


I need help because confused how to block form submit if no one checkbox checked.

var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');

$form.on('submit', function(e) {
  $.each($checkbox, function(index, value) {
    if (!$(value).is(':checked')) {
      alert('Opps! You not select friends.');
      e.preventDefault();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="send-invite-form">
  <input type="checkbox" class="invitation-friends" value="875" />
  <input type="checkbox" class="invitation-friends" value="394" />
  <button type="submit">Send</submit>
    </form>

The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.

Please help.


Solution

  • There is a way to do this that is much simpler than what you are doing. There's no need to loop. Just used the :checked pseudo-class selector to get a set of nodes that are checked and check the .length of the resulting set of nodes. If the .length is 0, no checkboxes have been checked.

    $( '#send-invite-form' ).on('submit', function(e) {
       if($( 'input[class^="invitation-friends"]:checked' ).length === 0) {
          alert( 'Oops! You not select friends.' );
          e.preventDefault();
       }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="send-invite-form">
         <input type="checkbox" class="invitation-friends" value="875" />
         <input type="checkbox" class="invitation-friends" value="394" />
    
         <button type="submit">Send</submit>
    </form>