0

I have multiple checkbox inputs that I am trying to create validation for. At least one checkbox has to be selected for the form to submit. What I did was add a hidden input. Then with a change function, there is a join function that combines the checkbox values. Under that there is a variable that checks for the checkboxes' length.

In the jQuery validate, I have tried requiring the field and the parent radio button that produces its associated checkboxes. Then the checkbox fields I have set a min of 1.

Currently, when I hit submit, the form goes through without any of the checkboxes being selected or the parent radio buttons.

Does anyone see what I am doing wrong?

$(document).ready(function() {
  var showMe = '';
  /*var checkLength = '';
  $('#interest').val(checkLength);
  console.log(checkLength);*/
  var newStatus = '';
  //Telling whether new is selected
  var usedStatus = '';
  //Telling whether used is selected
  var newSelPush = '';
  var usedSelPush = '';
  $('.equipmentOptionCont').change(function() {
    var newSel = [];
    var usedSel = [];
    //Get new mower options 
    $("input:checkbox[name=newMowerOption]:checked").each(function() {
      newSel.push($(this).val());
      newSelPush = newSel.join(', ');
    });
    //Get used mower options
    $("input:checkbox[name=usedMowerOption]:checked").each(function() {
      usedSel.push($(this).val());
      usedSelPush = usedSel.join(', ');
    });

    //Interest length creation for validation
    var interestCheck = (newSelPush || usedSelPush);
    //Hidden interest input value
    checkLength = interestCheck.length;
    console.log(checkLength);
    $('[name="interestHidden"]').val(checkLength);

  });

  //Validation

  $('#prodNotifForm').validate({
    onfocusout: true,
    rules: {
      interestHidden: {
        //required: true,
        required: $('#newMowerSelect').prop('checked') == true,
        min: 1
      }
    },
    messages: {
      interestHidden: {
        required: "Please choose at least one interest",
        min: "At least one interest needs chosen"
      }
    },
    errorPlacement: function(error, element) {
      if ($(element).attr('name') == 'interestHidden') {
        error.insertBefore(element.parent('div'));
      } else {
        error.insertAfter(element); // <- default
      }
    },
    submitHandler: function(form) {
      //Variables for the form ids
      var notifFirstName = $('#notifFirstName').val();

      $.ajax({
        url: 'subscriberNotifSend.php',
        type: 'POST',
        data: {
          'notif_first_name': notifFirstName,

        },
        success: function(data) {
          //console.log(data); // data object will return the response when status code is 
        },
        complete: function() {

        },
        error: function(xhr, textStatus, errorThrown) {
          alert(textStatus + '|' + errorThrown);
          //console.log('error'); //otherwise error if status code is other than 200.
        }
      });
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js"></script>
<form id="prodNotifForm">
  <div id="interestContainer">
    <input type="radio" name="notifymethod" id="newMowerSelect" class="equipmentMainSel notifCheck">
    <label for="newMowerSelect" class="checkMower">
         <div class="labelMowerSelect">New</div>
         <img src="" alt="New Mower Options" class="mowerOptionImgs">
        </label>
    <input type="radio" name="notifymethod" id="usedMowerSelect" class="equipmentMainSel notifCheck">
    <label for="usedMowerSelect" class="checkMower">
         <div class="labelMowerSelect">Used</div>
         <img src="" alt="Used Mower Options" class="mowerOptionImgs">
        </label>
    <div id="interestError"></div>
    <div id="newMowerOptions" class="equipmentOptionCont">
      <p class="notifQuestion">New Mower Options</p>
      <div class="equipmentWrap">
        <label class="equipmentOptions">Ferris</label>
        <input type="checkbox" name="newMowerOption" value="Ferris">
      </div>
    </div>
    <div id="usedMowerOptions" class="equipmentOptionCont">
      <p class="notifQuestion">Used Mower Options</p>
      <div class="equipmentWrap">
        <label class="equipmentOptions">Ferris</label>
        <input type="checkbox" name="usedMowerOption" value="Ferris">
      </div>
    </div>
    <div><input type="hidden" id="interestHidden" name="interestHidden" value=""></div>
  </div>
  <button id="notifSubmit">Sign up</button>
</form>
Sparky
  • 98,165
  • 25
  • 199
  • 285
Paul
  • 3,348
  • 5
  • 32
  • 76
  • You'll have to listen for the `
    `'s submit event and prevent it.
    – Titus Jun 28 '19 at 14:29
  • You are doing it wrong. You do not execute `$('#prodNotifForm').validate({` on click. You just do that on load. It will prevent the form from submitting unless the rules are passed: https://jqueryvalidation.org/documentation/ - remove `$('#notifSubmit').on('click', function(event) {` – mplungjan Jun 28 '19 at 14:32
  • @Titus Isn't this listening for it? `$('#notifSubmit').on('click', function(event) {` `#notifSubmit` is the submit button in the form. – Paul Jun 28 '19 at 14:32
  • @mplungjan When I took off the click function nothing different happened. The form still passes through without requiring the checkbox rules. – Paul Jun 28 '19 at 14:36
  • Is not listening for submit but you can still prevent the form from submitting by preventing this event (calling `event.preventDefault()`). – Titus Jun 28 '19 at 14:36
  • @Titus How do I make it listen for the form then? – Paul Jun 28 '19 at 14:38
  • All of the text inputs in the form are being validated and will stop the form from submitting if not filled in. So I'm not sure how the checkboxes aren't doing the same, when they are in the same form. – Paul Jun 28 '19 at 14:48
  • @paul I made a snippet and fixed the missing end brackets and remove the click. You can now actually test the form – mplungjan Jun 28 '19 at 15:13
  • @mplungjan Thanks. This might be easier though - if you go to the link included in this comment. https://optimumwebdesigns.com/admin/gsa/form ... click on the green button to see the form. – Paul Jun 28 '19 at 15:14
  • We really really like a [mcve] here. For example you are missing `notifFirstName` in the posted code – mplungjan Jun 28 '19 at 15:16
  • @mplungjan I reduced the code for the question here because the notifFirstName validation is working fine. On the example site, I removed the click function and it changed nothing. – Paul Jun 28 '19 at 15:19
  • I get `jquery.validate.min.js:4 Uncaught TypeError: e[d].call is not a function` – mplungjan Jun 28 '19 at 15:27
  • @mplungjan I'm not sure why that error displays. The name fields still are validated when that error displays. I honestly have no idea what else to try. – Paul Jun 28 '19 at 15:52

0 Answers0