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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With