gpt4 book ai didi

javascript - 仅使用 typeahead.js 强制有效输入

转载 作者:行者123 更新时间:2023-11-30 17:41:35 25 4
gpt4 key购买 nike

我有一些带有 twitters typeahead.js(不是旧的 bo​​otstrap typeahead)的文本框,用于从自定义 REST 服务自动完成业务数据。如何强制文本框具有有效选择或根本没有文本?我想在提交前验证表单,但我无法访问从服务器获取的数据集。

我试图连接到已关闭的事件,但似乎无法访问要验证的数据集。目前我只看到 2 种可能的解决方案:

  1. 连接到选定和自动完成的事件并将最后一个有效值存储在一个额外的隐藏文本框中,并根据这些值验证文本框。

  2. 或者通过额外的 rest 调用(我尽量避免)来验证针对服务器的输入

谁有更好的解决方案?

最佳答案

我自己在搜索类似内容时发现了这篇文章。我正在尝试确保用户根据提供的预取预取的自动完成数据进行有效选择。这是我的代码。它适用于浏览器验证。

var engine = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: '/data/professions.json',
filter: function(list) {
return $.map(list, function(professions) { return { name: professions }; });
}
}
});

// kicks off the loading/processing of `local` and `prefetch`
engine.initialize();

$('#professionsTypeahead').typeahead(null, {
name: 'professions',
displayKey: 'name',
source: engine.ttAdapter()
}).blur(function(){
match = false
for (var i = engine.index.datums.length - 1; i >= 0; i--) {
if($(this).val() == engine.index.datums[i].name){
match = true;
}
};
if(!match){
alert("Invalid Selection")
}
});

在 .blur 函数上,您可以检查数据集以查看是否存在匹配项,如果没有匹配项,您可以随心所欲地处理它。比如清除文本框等

关于javascript - 仅使用 typeahead.js 强制有效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20972783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com