[英]Jquery Validate require at least 1 checkbox if text field has a value
使用 jQuery Validate 在驗證場景中掙扎。 如果文本字段有值,我需要至少檢查 1 個復選框。 我已經找到了如何單獨要求一組中至少一個復選框,但不是基於來自不同字段的值。
<input type="checkbox" name="a" value="x">
<input type="checkbox" name="b" value="y">
<input type="checkbox" name="c" value="z">
<input type="text" name="textfield">
如果“文本字段”中有任何值,則必須至少選中三個復選框中的一個。 如果“文本字段”中沒有值,則可以選中或不選中復選框 - 不需要。
<form id="myform">
<input type="checkbox" class="foo" name="a" value="x">
<input type="checkbox" class="foo" name="b" value="y">
<input type="checkbox" class="foo" name="c" value="z">
<input type="text" name="textfield">
<input type="submit">
</form>
$(document).ready(function() {
$('#myform').validate({
rules: {
a: {
require_from_group: function() {
if ($('[name="textfield"]').is(':filled')) {
return [1, ".foo"];
}
}
},
b: {
require_from_group: function() {
if ($('[name="textfield"]').is(':filled')) {
return [1, ".foo"];
}
}
},
c: {
require_from_group: function() {
if ($('[name="textfield"]').is(':filled')) {
return [1, ".foo"];
}
}
},
textfield: {
required: true
}
},
errorPlacement: function(error, element) {
error.insertBefore(element);
}
});
});
你可以看看這個,希望對你有幫助
let checkBox_i = $("input[name='a']"); let checkBox_ii = $("input[name='b']"); let checkBox_iii = $("input[name='c']"); let text = $("input[name='textfield']"); $(':input').on('input', validateInput) function validateInput() { let a = text.val().trim(); let b = checkBox_i.is(':checked'); let c = checkBox_ii.is(':checked'); let d = checkBox_iii.is(':checked'); //checks if text extsts and checks any one of checkbox is checked if (a.length > 0 && (b || c || d)) { //your code $('.validStatus').text('valid input'); } else { //uncheck checkbox if input is removed checkBox_i.prop('checked', false); checkBox_ii.prop('checked', false); checkBox_iii.prop('checked', false); //alert user for invalid input $('.validStatus').text(''); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" name="a" value="x"> <input type="checkbox" name="b" value="y"> <input type="checkbox" name="c" value="z"> <input type="text" name="textfield"> <div class='validStatus'></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.