[当前,我正在使用jQuery验证插件,该插件通过输入字段内的简单必需关键字激活。但是,当我要在动态创建的复选框字段中使用它时,它只是要求选中所有复选框。但我希望至少需要选中一个复选框。
{% for opt in obj.option_array_a %}
<label>
<input class="optcheckbox" name="optcheckbox_{{ obj.question_number }}"
id="{{ obj.id }}__{{ forloop.counter0 }}" type="checkbox"
value="{{ opt }}"/> <span>{{ opt }}</span><br>
</label>
{% endfor %}
这里是如何检查是否至少选中了一个复选框的示例。
$( document ).ready(function() {
$('input[name="question_1"]').change(function(){
$('#result').text($('input[name="question_1"]:checked').length > 0 ? "OK" : "KO");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="question_1" value="answer 1" /> Answer 1
<input type="checkbox" name="question_1" value="answer 2" /> Answer 2
<div id="result"></div>
首先,将相同的name
属性添加到所有复选框,并添加一个名为required-chk
的类,例如:
<input name="optcheckbox" type="checkbox" value="true" class="required-chk" />
然后您可以添加一个自定义验证器,以检查是否至少选中一次复选框,例如:
$.validator.addMethod('require-one', function(value) {
return $('.required-chk:checked').length > 0;
}, 'Please select atleast one option.');
然后如下更新.validate({...})
功能:
$.validator.addMethod('require-one', function(value) {
return $('.required-chk:checked').length > 0;
}, 'Please select atleast one option.');
$("#myForm").validate({
rules: {
optcheckbox: 'require-one',
},
errorPlacement: function(error, element) {
$('#form_error').append(error);
},
submitHandler: function(form) {
alert('Form Submited');
return false;
}
});
label.error { color: red; margin: 10px 0; vertical-align: top; display:block }
<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.min.js"></script>
<form id="myForm">
<h4>Select atleast one option:</h4>
<input name="optcheckbox" type="checkbox" value="true" class="required-chk" />
<label>Question 1</label>
<input name="optcheckbox" type="checkbox" value="true" class="required-chk" />
<label>Question 2</label>
<input name="optcheckbox" type="checkbox" value="true" class="required-chk" />
<label>Question 3</label>
<div class="error" id="form_error"></div>
<br />
<input type="submit" />
</form>
使用HTML5单选按钮组验证:
<form>
Select Gender:
<label><input type="radio" name="gender" value="male" required>Male</label>
<label><input type="radio" name="gender" value="female">Female</label>
<label><input type="radio" name="gender" value="other">Other</label>
<input type="submit">
</form>