HTML表单验证 - 基于单选按钮选择的条件 [英] HTML Form Validation - Conditional based on radio button selection
问题描述
我有一个HTML表单,我正在使用JQuery Validate插件来要求某些表单字段是必需的。我有一个带有3个选项的单选按钮字段:
I have an HTML form and I'm using the JQuery Validate plugin to require some form fields to be mandatory. I have a radio button field with 3 options:
小时
天数
不确定
Hours Days Unsure
和另一个字段输入对应于小时或天数选择的数字。但是,如果用户选择不确定,则不需要输入数字。如果用户没有选择不确定(即当他们选择小时或天时),我无法弄清楚如何仅强制数字字段。这是我的HTML:
and another field to enter a number that corresponds to the hours or days selections. However if the user selects "Unsure" they are not required to enter a number. I can't work out how to only make the number field mandatory if the user doesn't select "Unsure" (i.e. when they select either "Hours" or "Days"). Here's my HTML at the moment:
<form role="form" action="continue.php" method="post" id="durationForm">
<tr>
<td colspan = "3">Please enter the duration?</td>
</tr>
<tr>
<td width="10%"><input type="number" class="form-control" id="duration" name="durationNumber" required></td>
<label for="duration" class="validateError"></label>
<td width="50%">
<div class="controls">
<label class="radio">
<input type="radio" name="duration" id="duration" value="Hours" required> Hours</label>
<label class="radio">
<input type="radio" name="duration" id="duration" value="Days" required> Days</label>
<label class="radio">
<input type="radio" name="duration" id="duration" value="Unsure" required> Unsure</label>
<label for="duration" class="validateError"></label>
</div>
</td>
</tr>
<button type="submit" class="btn btn-primary">Next</button>
</form>
这是脚本:
$(document).ready(function () {
$("#durationForm").validate({
errorClass: "validateError"
});
});
我设置了 jsfiddle 也显示了这一点。
I've setup a jsfiddle that shows this as well.
推荐答案
来自: https://stackoverflow.com/a/19546185/1477051
jQuery直接验证支持这一点,使用依赖
表达式。
jQuery Validate actually directly supports this, using dependency expressions.
您需要做的就是更改这样的验证选项:
All you need to do is change your validate options like this:
$('#myform').validate({
rules: {
fieldA: {
required:'#checkA:checked'
}
}
});
就是这样!
我是在这里使用它代码: http://jsfiddle.net/xJBX9/1/
I've used it on your code here: http://jsfiddle.net/xJBX9/1/
这篇关于HTML表单验证 - 基于单选按钮选择的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!