Creating a jQuery UI autocomplete widget * actually * autocomplete

I need autocomplete in the application I'm working on, and since I'm already using the jQuery user interface, I am trying to make the Autocomplete widget fit my needs.

Step one is to make the search query a match only at the beginning of the proposed conditions. I already have this work, as you can see in the code below. The second step is for the first sentence to be virtually autocomplete.

Which probably needs a little explanation. When I hear โ€œautocompleteโ€, I suppose to enter โ€œfโ€ and change the contents of the text field to โ€œfooโ€, selecting โ€œooโ€ so that it will be replaced if I type in another character and leave it in the if field. I exit it. I usually call what the Autocomplete widget offers, not autocomplete.

After seeing how Autocomplete works, I think the autocompleteopen event is the right place to do this (it is called every time the list of offers is updated), but I donโ€™t understand how to access the list of offers from there.

Any thoughts?

 $("#field").autocomplete({ delay: 0, source: function filter_realms(request, response) { var term = request.term.toLowerCase(); var length = term.length; response($.grep(candidates, function(candidate) { return candidate.substring(0, length).toLowerCase() === term; })); }, open: function(event, ui) { // magic happens here? } }); 
+7
jquery jquery-ui autocomplete
source share
2 answers

Got it. I forgot that widgets can be accessed via .data() .

 $("#field").autocomplete({ delay: 0, source: function filter_realms(request, response) { var term = request.term.toLowerCase(); var length = term.length; response($.grep(candidates, function(candidate) { return candidate.substring(0, length).toLowerCase() === term; })); }, open: function(event, ui) { var current = this.value; var suggested = $(this).data("autocomplete").menu.element.find("li:first-child a").text(); this.value = suggested; this.setSelectionRange(current.length, suggested.length); } }); 
+6
source share

I took part of the length check and changed the filter function in the search. This way you can take advantage of UI JSON processing.

  filter: function(array, term) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" ); var smatcher = term.toLowerCase(); var length = smatcher.length; return $.grep( array, function(value) { if(value.label.substring(0, length).toLowerCase() == smatcher){ return matcher.test( value.label || value.value || value ); } }); 
0
source share

All Articles