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 require the field and have a min of 1 setup.
Currently, when I hit submit, the form goes through without any of the checkboxes being selected.
Does anyone see what I am doing wrong?
HTML
<div id="interestError"></div>
<div class="equipmentWrap">
<label class="equipmentOptions">Walker</label>
<input type="checkbox" name="usedMowerOption" value="Walker">
</div>
<div style="display: none">
<input type="hidden" name="interestHidden" id="interestHidden">
</div>
JS
//Interest length creation for validation
var interestCheck = (newSelPush || usedSelPush);
$('#interest').val(interestCheck);
//Hidden interest input value
var checkLength = interestCheck.length;
console.log(checkLength);
$('[name="interestHidden"]').val(checkLength);
//Validation
$('#notifSubmit').on('click', function(event) {
$('#prodNotifForm').validate({
onfocusout : true,
rules: {
interestHidden: {
required: 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
$.ajax({
url: 'subscriberNotifSend.php',
type: 'POST',
data: {
'notif_first_name': notifFirstName,
},
success: function(data) {
}
}
});
}
});
});
Update - code from the change 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);
$('#interest').val(interestCheck);
//Hidden interest input value
checkLength = interestCheck.length;
console.log(checkLength);
$('[name="interestHidden"]').val(checkLength);
});