我有一个简单的html表单,我已经使用JQuery Validation插件添加了验证。我让它适用于需要值的单个字段。我现在需要对其进行扩展,以便如果用户对问题回答“是”,则必须在“详细信息”字段中输入内容,否则“详细信息”字段可以留空。我正在使用单选按钮显示是/否。这是我完整的html表单 - 我不确定从哪里开始:
<script type="text/javascript" charset="utf-8">
$.metadata.setType("attr", "validate");
$(document).ready(function() {
$("#editRecord").validate();
});
</script>
<style type="text/css">
.block { display: block; }
form.cmxform label.error { display: none; }
</style>
</head>
<body>
<div id="header">
<h1>
Questions</h1>
</div>
<div id="content">
<h1>
Questions Page 1
</h1>
</div>
<div id="content">
<h1>
</h1>
<form class="cmxform" method="post" action="editrecord.php" id="editRecord">
<input type="hidden" name="-action" value="edit">
<h1>
Questions
</h1>
<table width="46%" class="record">
<tr>
<td width="21%" valign="top" class="field_name_left"><p>Question 1</p></td>
<td width="15%" valign="top" class="field_data">
<label for="Yes">
<input type="radio" name="Question1" value="Yes" validate = "required:true" /> Yes
</label>
<label for="No">
<input type="radio" name="Question1" value="No" /> No
</label>
<label for="Question1" class="error">You must answer this question to proceed</label>
</td>
<td width="64%" valign="top" class="field_data"><strong>Details:</strong>
<textarea id = "Details1" class="where" name="Details1" cols="25" rows="2"></textarea></td>
</tr>
<tr>
<td valign="top" class="field_name_left">Question 2</td>
<td valign="top" class="field_data">
<label for="Yes">
<input type="radio" name="Question2" value="Yes" validate = "required:true" /> Yes
</label>
<label for="No">
<input type="radio" name="Question2" value="No" /> No
</label>
<label for="Question2" class="error">You must answer this question to proceed</label>
</td>
<td valign="top" class="field_data"><strong>Details:</strong>
<textarea id = "Details2" class="where" name="Details2" cols="25" rows="2"></textarea> </td>
</tr>
<tr class="submit_btn">
<td colspan="3">
<input type="submit" name="-edit" value="Finish">
<input type="reset" name="reset" value="Reset"> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
答案 0 :(得分:19)
在<textarea>
个元素上,为dependency expression添加required
,例如问题1,请执行以下操作:
validate="required:'input[name=Question1][value=Yes]:checked'"
这表示如果$('input[name=Question1][value=Yes]:checked').length > 0
需要该字段,那么如果选中是,则需要:)
答案 1 :(得分:15)
您可以这样做:
$("#editRecord").validate({
rules: {
'Details1': {
required: function() {
return $('input[name=Question1]').val() == 'yes';
}
}
'Details2': {
required: function() {
return $('input[name=Question2]').val() == 'yes';
}
}
}
});
答案 2 :(得分:0)
回应上面提出的Nick Craver的建议回应,我找到了正确的语法:
类=&#34;验证[需要] [名称=问题1] [值=是]:检查&#34;
而不是他发布的内容。
感谢你让我走上正轨!