我正在使用jQuery Validation plugin并尝试验证两个时间字段。我想确保如果一个字段选择“全部”,则另一字段也适用,并且结束时间
大于开始时间
这是 HTML:
<form id="schedule">
<select name='start_hour' id='start_hour'>
<option value='All00'>All</option>
<option value='0000'>00</option>
<option value='0100'>01</option>
<option value='0200'>02</option>
<option value='0300'>03</option>...
</select>
and
<select name='end_hour' id='end_hour'>
<option value='All00'>All</option>
<option value='0000'>00</option>
<option value='0100'>01</option>
<option value='0200'>02</option>
<option value='0300'>03</option>...
</select>
</form>
这是自定义规则:
jQuery.validator.addMethod( "schedule", function(value, element) {
var start_hour = document.getElementsByName("start_hour");
var end_hour = document.getElementsByName("end_hour");
alert(start_hour.value);
alert(end_hour.value);
if (start_hour.value == "All00" && end_hour.value !="All00")
{
alert('end hour all error')
return false;
}
else if (end_hour.value == "All00" && start_hour.value !="All00")
{
alert('start hour all error')
return false;
}
else if (end_hour.value <= start_hour.value ){
alert('end hour must be larger error')
return false;
}
else return true;
}, "Error with schedule");
出于某种原因alert(start_hour.value);
返回“undefined”我也尝试使用getElementbyID
但也失败了。我对 Javascript 很陌生,所以我知道这可能很简单。
<强> JsFiddle Here
最佳答案
您不需要将 getElementsByName 与 jQuery 一起使用 试试这个,jQuery Attribute Selector
$('select[name="start_hour"]')
或者由于您的 id 似乎与名称相同,您可以改用此选择器
$('select#start_hour')
您的验证器方法应该像这样构建
jQuery.validator.addMethod( "schedule", function(value, element) {
var start_hour = $('select#start_hour');
var end_hour = $('select#end_hour');
alert(start_hour.val());
alert(end_hour.val());
if (start_hour.val() == "All00" && end_hour.val() !="All00") {
alert('end hour all error')
return false;
}
else if (end_hour.val() == "All00" && start_hour.val() !="All00") {
alert('start hour all error')
return false;
}
else if (end_hour.val() <= start_hour.val() ) {
alert('end hour must be larger error')
return false;
}
else return true;
}, "Error with schedule");
关于javascript - 无法使用自定义 jQuery 表单下拉验证选择 GetElementByName 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037479/