【发布时间】:2011-05-21 21:06:24
【问题描述】:
我有一个搜索表单,其中显示不同组的复选框,具体取决于用户在下拉列表中选择的内容。我想使用 jQuery 验证插件来检查用户是否 (a) 在下拉列表中选择了某些内容,并且 (b) 至少选中了一个复选框。
我已经让这个工作了,除了复选框的验证消息表现得很奇怪。用户可以毫无问题地在下拉列表中选择一个值,但是当用户点击页面上的anything(甚至是空白区域)时,会显示复选框的验证错误消息。有谁知道可能是什么原因造成的?
这是我的验证插件的 JS 代码。我选择让所有验证消息显示在下拉列表(名称='to')旁边,而不是复选框旁边(它们都有 class='from_checkbox')。
$(document).ready(function(){
// Method for verifying that at least one checkbox has been checked
jQuery.validator.addMethod("atLeastOneChecked", function(value, element, params) {
return $('.from_checkbox:checked').length > 0;
}, jQuery.format("From?"));
// Tell jQuery validation plugin to validate the search form with the proper rules
$("#search_form").validate({
rules: {
'to': {
required: true,
atLeastOneChecked: true
}
},
messages: {
'to': {
required: "To?"
}
}
});
});
大部分 html 是由 php 生成的,但输出看起来像这样:
<form action="results.php" method="post" id="search_form">
<table>
<tr>
<td>Destination</td>
<td>
<select name="to" onchange='changeFromDiv(options[selectedIndex].value)'>
<option disabled="disabled" selected value="">--select--</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" id="from_label">Which cities can you travel from?</td>
</tr>
<tr>
<td colspan="2">
<div style="display:none" class="from_div" id="from_1">
<input name="from[3]" type="checkbox" value="3" class="from_checkbox" /> City 3<br />
<input name="from[4]" type="checkbox" value="4" class="from_checkbox" /> City 4<br />
<input name="from[8]" type="checkbox" value="8" class="from_checkbox" /> City 8<br />
</div>
<div style="display:none" class="from_div" id="from_2">
<input name="from[1]" type="checkbox" value="1" class="from_checkbox" /> City 1<br />
<input name="from[6]" type="checkbox" value="6" class="from_checkbox" /> City 6<br />
</div>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" id="submit_button" value="Find best route" onclick="showLoading()" />
</td>
</tr>
</table>
</form>
【问题讨论】:
-
刚刚编辑了问题以包含 html。如果您想查看任何其他代码(例如用于显示和隐藏带有复选框的 div 的 JS),请告诉我,我会包含它。
-
验证插件通常会在失去焦点时检查字段,对吧?也就是说,当您单击页面上的其他任何位置时,正如您所描述的那样。我敢打赌,它正在按预期工作。
-
哦!我没有意识到这一点。你知道有没有办法让它等到用户点击提交按钮?
-
看看我的回答 - 我认为这就是你所要做的。
标签: javascript jquery validation forms