How to implement "mustMatch" and "selectFirst" in jQuery UI Autocomplete?
I think I solved both features...
To make things easier, I used a common custom selector:
$.expr[':'].textEquals = function (a, i, m) {
return $(a).text().match("^" + m[3] + "$");
};
The rest of the code:
$(function () {
$("#tags").autocomplete({
source: '/get_my_data/',
change: function (event, ui) {
//if the value of the textbox does not match a suggestion, clear its value
if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
$(this).val('');
}
}
}).live('keydown', function (e) {
var keyCode = e.keyCode || e.which;
//if TAB or RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
if((keyCode == 9 || keyCode == 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0)) {
$(this).val($(".ui-autocomplete li:visible:first").text());
}
});
});
If any of your autocomplete suggestions contain any 'special' characters used by regexp, you must escape those characters within m[3] in the custom selector:
function escape_regexp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
and change the custom selector:
$.expr[':'].textEquals = function (a, i, m) {
return $(a).text().match("^" + escape_regexp(m[3]) + "$");
};
I found this question to be useful.
I thought I'd post up the code I'm now using (adapted from Esteban Feldman's answer).
I've added my own mustMatch option, and a CSS class to highlight the issue before resetting the textbox value.
change: function (event, ui) {
if (options.mustMatch) {
var found = $('.ui-autocomplete li').text().search($(this).val());
if (found < 0) {
$(this).addClass('ui-autocomplete-nomatch').val('');
$(this).delay(1500).removeClass('ui-autocomplete-nomatch', 500);
}
}
}
CSS
.ui-autocomplete-nomatch { background: white url('../Images/AutocompleteError.gif') right center no-repeat; }
I used something as simple as this for mustMatch and it works. I hope it helps someone.
change: function (event, ui) {
if (!ui.item) {
$(this).val('');
}
}
I think I got the mustMatch working with this code... It needs thorough test though:
<script type="text/javascript">
$(function() {
$("#my_input_id").autocomplete({
source: '/get_my_data/',
minChars: 3,
change: function(event, ui) {
// provide must match checking if what is in the input
// is in the list of results. HACK!
var source = $(this).val();
var found = $('.ui-autocomplete li').text().search(source);
console.debug('found:' + found);
if(found < 0) {
$(this).val('');
}
}
});
});
</script>