我正在使用jQuery Validator在提交之前需要一个文本输入字段。表格如下:
当用户在地理位置成功之前以及在输入字段中输入任何内容之前单击提交时,我发现问题。表单正确无法验证,但是当地理位置成功并成功填充输入字段(并且表单已成功重新验证)时,如果用户然后单击“提交”,则输入字段将重置为空白并且验证失败。
我无法看到导致该字段重置的原因。是jQuery验证器吗?如何在重新提交时停止重置?
以下是相关代码:
表单(样式已删除):
<form action='/find' id='search-form' method='post' role='form'>
<select id='what' name='what'>
<option>...</option>
</select>
<input id='where' name='where' type='text'>
<button id='search-form-submit' type='submit'>Search</button>
</form>
jQuery代码:
jQuery.validator.setDefaults({
success: "valid"
});
$('#search-form').validate({
rules: {
where: {
required: true
}
},
highlight: function(element) {
$(element).addClass('error');
},
success: function(element) {
$(element).removeClass('error');
},
errorPlacement: function(){
return false;
}
});
在地理位置成功时,执行:
if (!document.getElementById('where').value) { // if user hasn't typed anything yet...
document.getElementById('where').value = postcode; // populate with the geolocated postcode
var validator = $('#search-form').validate();
validator.element("#where"); // revalidate the form field (this works)
}
答案 0 :(得分:0)
引用标题:
&#34;停止jQuery表单验证重置由其他JavaScript填充的typeahead.js输入字段&#34;
问题的前提是有缺陷的。 jQuery Validate插件中没有任何内容可以改变数据输入字段的值。这取决于用户或代码中的其他位置。
引用OP:
&#34;我无法看到导致该字段重置的原因。&#34;
我也不能。也许它不在您提供的代码中。否则,这是您展示的唯一一个会改变输入字段值的单一内容......
document.getElementById('where').value = postcode;
旁注:
1)unhighlight
回调函数是对highlight
函数的补充,而不是success
。 success
回调通常用于处理&#34;有效&#34;上的常隐隐藏错误label
。字段,就像显示复选标记一样。
您的代码看起来应该更像......
highlight: function(element) {
$(element).addClass('error');
},
unhighlight: function(element) {
$(element).removeClass('error');
},
2)而不是所有这些...
var validator = $('#search-form').validate();
validator.element("#where");
只需使用the .valid()
method ...
$('#where').valid();
.valid()
演示:http://jsfiddle.net/LrS32/
答案 1 :(得分:0)
事实证明,这是由typeahead.js引起的,我没有看到它是相关的(尽管现在已经非常明显了)。
解决方案似乎是在更新输入字段值时设置typeahead.js查询,在这种情况下:
$('#where').typeahead('setQuery', postcode);
我对这个问题反对了一段时间,所以我希望别人觉得这很有帮助。