我尝试创建多个复选框输入。至少需要选中一个复选框才能提交表单。我所做的就是添加了隐藏的输入。然后,通过更改功能,有一个合并功能将复选框值组合在一起。在其下有一个变量,用于检查复选框的长度。
在jQuery验证中,我需要该字段,并且至少要设置1个。
当前,当我点击“提交”时,该表单将通过而未选中任何复选框。
有人看到我在做什么错吗?
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) {
}
}
});
}
});
});
更新-更改功能中的代码:
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);
});