验证 jquery 自动完成
我有一个带有远程数据源的文本框,用于自动完成(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题缺乏细节,但我假设您的意思是在客户端进行验证,因为您明确提到了自动完成插件。这个答案将分为两个部分。第一个是原始答案,假设有一个自动完成插件。第二个是根据问题的更新进行修订的。
1)使用 http://docs.jquery.com/Plugins/Autocomplete
最好的解决方案是“mustMatch”选项。以下是 API 文档。
您应该能够以这种方式使用它:
您还可以在“结果”事件中以某种方式验证用户输入。这是一个链接: http://docs.jquery.com/Plugins/Autocomplete/result 。
2)使用http://jqueryui.com/demos/autocomplete
这里没有mustMatch选项。您可以扩展该插件,或者可以添加类似于我为其他自动完成插件提到的内容。使用“更改”事件。
如果您使用数组作为数据源,这会更有效。由于您使用的是远程数据源,因此您需要使用 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.
You should be able to use it in this way:
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.
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.