我怎样才能让typeahead.js与jquery.validate一起很好地玩? [英] How can I get typeahead.js to play nicely with jquery.validate?
问题描述
我有一个使用jQuery验证的ASP.NET MVC 5网站(在MVC项目模板中为jquery.validate.js
).我正在尝试使用typeahead.js
在表单中的输入字段之一上实现预输入功能. (该表单恰好在引导程序模式内).
I have an ASP.NET MVC 5 website that uses jQuery validation (jquery.validate.js
in the MVC project template). I'm trying to use typeahead.js
to implement type-ahead functionality on one of the input fields in a form. (The form happens to be inside a bootstrap modal).
由于提交表单将发出AJAX请求,因此表单提交事件将被捕获,如下所示:
Because submitting the form will make an AJAX request, the form submit event is trapped like so:
$form.on("submit", function (e) {
if (!$form.valid()) {
return false;
}
... do stuff ...
请注意,这里发生的第一件事是检查表单,以检查是否有jQuery验证库检测到的任何验证错误.
Note that the first thing that happens here is that the form is checked for any validation errors, as detected by the jQuery validation library.
如果我不使用typeahead
,那么一切都很好.我可以在表单中输入值并提交,一切都很好.
If I don't use typeahead
, then everything is fine. I can enter values into my form and submit it, and all is well.
但是,只要执行以下操作,即可在输入中添加预输入功能:
However, as soon as I do the following to add type-ahead functionality to my input:
$("#myInput").typeahead({
minLength: 1,
highlight: true
},
{
source: mySource
});
...然后我将无法再提交该表单.我的表单被认为是无效有效:$form.valid()
返回false
.
...then I can no longer submit the form. My form is considered to be not valid: $form.valid()
returns false
.
我认为typeahead.js
库正在向表单添加一些额外的元素(包括隐藏的输入),这使jquery.validate.js
库感到困惑.
I think the typeahead.js
library is adding some extra elements (including a hidden input) to the form, and this is confusing the jquery.validate.js
library.
使用Chrome F12,似乎那里的输入看起来像是原始输入的副本,可悲的是,该副本似乎已被复制,因此它也具有所有jQuery-validation属性的副本.
Using Chrome F12, it seems there's an input there that looks like a copy of the original input, and sadly that copy appears to have been duplicated such that it also has copies of all the jQuery-validation attributes.
我该如何解决?
推荐答案
这似乎可行(在调用typeahead()
之后立即放置:
This seems to work (placed immediately after the call to typeahead()
:
$("input.tt-hint").removeAttr("data-val data-val-required data-val-maxlength data-val-maxlength-max");
这篇关于我怎样才能让typeahead.js与jquery.validate一起很好地玩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!