Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery UI autocomplete - results not shown when input does not match resultset
    text
    copied!<h3>Short version of Problem</h3> <p>Autocomplete works when the input string matches the result string, but not otherwise. The data are succesfully retreived from JSON. </p> <h3>Longer version</h3> <p>I want to dynamicly edit the source content of the autocomplete with JSON data. </p> <p>The approach below works when the search string matches the first_name and last_name field.</p> <p>But the JSON url returns more, e.g. with search on username it still returns correct data. But this is not shown in autocomplete, and <em>my theory is that autocomplete UI forces the 'input value' to be the same as the 'result value'</em>. </p> <h3>JSON data returns:</h3> <pre><code>[ {"pk": 1012912, "fields": {"first_name": "Barack", "last_name": "Obama"}}, {"pk": 1017519, "fields": {"first_name": "George", "last_name": "Bush"}} ] </code></pre> <h3>The autocomplete code</h3> <p>As you can see the result set is set by the search function. </p> <hr> <pre><code>$('#search').autocomplete({ source: [], search: function(event, ui){ results = []; var json = jQuery.getJSON('http://jsondata.com?query='+event.target.value, function(data){ for (var i=0; i&lt;data.length; i++){ results.push(data[i].fields.first_name + ' ' +data[i].fields.last_name); }; }).success(function(){ $('#search').autocomplete('option', 'source', results); //The following debug proves that the 'results' are correct, even on search for usernames console.log(results); }); }, }); </code></pre> <p>If I search for 'Barack Obama' in the #search field, I get my results, no problem. However, if say Barack Obama had the username 'baracko' and I search for his username, then I get the correct results from the JSON and in the results array (as I checked this with console.log) but the results are not shown.</p> <p>Anyone have the idea why?</p> <h2>Solution for future googlers or those intrested</h2> <p>Thanks to some hints by ek_ny here is my new JSON: </p> <pre><code>[{ 'value' : 'Barack Obama'}, { 'value' : 'George Bush'}] </code></pre> <p>And here is the code:</p> <pre><code>$('#search').autocomplete({ source: function(req, res){ jQuery.getJSON('http://jsondata.com/?query='+req.term, req, function(data){ var results = []; $.each(data, function(i, val){ results.push(val.value) }); //Add results to callback res(results); }); }, }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload