text field auto-complete - only allow submissions within autocomplete options
I am looking for code that allows an autocomplete, only within a specified data array. So only data within the auto complete array is allowed to be entered. Not sure where 开发者_如何学Goto start looking.
Thanks!
The following solution, which utilises jQuery UI Autocomplete, should suffice - of course it might need some further tweaking depending on your specific requirements.
Markup:
<input id="autocomplete"/>
<br />
<input id="submit" type="submit" disabled="disabled"/>
Script:
var source = ['One', 'Two', 'Three', 'Four'];
$("input#autocomplete").autocomplete({
source: source,
select: function(event, ui) {
$("#submit").removeAttr("disabled");
}
}).keyup(function() {
var $parentContext = $(this);
var matches = $.grep(source, function(n, i) {
return $parentContext.val().toLowerCase() == n.toLowerCase();
});
$("#submit").attr("disabled", !matches.length);
});
Demo: http://jsfiddle.net/karim79/Ezbns/
Further reading:
- http://jqueryui.com/demos/autocomplete/
- http://api.jquery.com/jQuery.grep/
精彩评论