验证 jquery 自动完成

发布于 2024-10-06 17:50:11 字数 176 浏览 0 评论 0原文

我有一个带有远程数据源的文本框,用于自动完成(jquery)[不是插件,原始插件显示在 jquery ui演示] 如何确保用户仅键入自动完成建议之一中的内容,而不键入他自己的内容?

I have a textbox with remote datasource for autocomplete(jquery) [not the plugin, the original one shown in jquery ui demos ]
How do I make sure user typed only what was in one of autocomplete suggestions and nothing of his own ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请止步禁区 2024-10-13 17:50:11

这个问题缺乏细节,但我假设您的意思是在客户端进行验证,因为您明确提到了自动完成插件。这个答案将分为两个部分。第一个是原始答案,假设有一个自动完成插件。第二个是根据问题的更新进行修订的。

1)使用 http://docs.jquery.com/Plugins/Autocomplete

最好的解决方案是“mustMatch”选项。以下是 API 文档

如果设置为 true,自动完成程序将仅允许后端呈现的结果。请注意,非法值会导致输入框为空。

您应该能够以这种方式使用它:

$("selector").autocomplete("url", {"mustMatch": true});

您还可以在“结果”事件中以某种方式验证用户输入。这是一个链接: http://docs.jquery.com/Plugins/Autocomplete/result

2)使用http://jqueryui.com/demos/autocomplete

这里没有mustMatch选项。您可以扩展该插件,或者可以添加类似于我为其他自动完成插件提到的内容。使用“更改”事件。

$( ".selector" ).autocomplete({
   change: function(event, ui) { ... }
});

如果您使用数组作为数据源,这会更有效。由于您使用的是远程数据源,因此您需要使用 ui.item 执行另一个最终查询来验证用户值。然后您可以允许或拒绝默认行为。

无论哪种情况,输入仍应在服务器端以某种方式进行验证。这超出了 jQuery 插件的范围。

The question is lacking specifics, but I will assume you mean validate on the client side since you referred explicitly to the auto complete plugin. This answer will have two parts. The first is the original answer, assuming one autocomplete plugin. The second is revised based on updates to the question.

1) Using http://docs.jquery.com/Plugins/Autocomplete

The best solution for this is the "mustMatch" option. Here is the API documentation.

If set to true, the autocompleter will only allow results that are presented by the backend. Note that illegal values result in an empty input box.

You should be able to use it in this way:

$("selector").autocomplete("url", {"mustMatch": true});

You can also validate the user input in some way in the "result" event. Here is a link: http://docs.jquery.com/Plugins/Autocomplete/result .

2) Using http://jqueryui.com/demos/autocomplete

There is no mustMatch option here. You could extend the plugin, or you could add something similar to what I mentioned for the other autocomplete plugin. Use the "change" event.

$( ".selector" ).autocomplete({
   change: function(event, ui) { ... }
});

If you were using an array as a datasource, this would be more efficient. Since you are using a remote data source you would need to do another final query using ui.item to validate the user value. You can then allow or deny the default behavior.

In either case, the input should still be validated in some way on the server side. This is out of the scope of jQuery plugins.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文