jQuery UI autocomplete, show something when no results - jquery-ui

I have the following code:
// Autocomplete search
$("#shop_search").autocomplete({
source: '<%= spotify_search_path(:json) %>',
minLength: 1,
select: function(event, ui) {
append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web);
$("#shop_search").val('');
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + "<span class='autocomplete_link'>" + item.name + "</span>" + "<br />" + "<span class='autocomplete_address'>" + item.address_geo + "</span>" + "</a>" )
.appendTo( ul );
$(".ui-autocomplete-loading").ajaxStart(function(){
$(this).show();
});
$(".ui-autocomplete-loading").ajaxStop(function(){
$(this).hide();
});
};
Currently it only shows the drop down autocomplete when there is search result. I want it to show "No matches found" when nothing could be found. What should I add into the code?
Thanks.

If you use a jQuery ajax call for the source, you can append "No results found" to the results if there aren't any. Then on the select method, you can simply check to see if the item is the "no results found" item that you added and if so, do nothing. Here I identified that by checking to see if the id was equal to zero.
$("#shop_search").autocomplete({
source: function (request, response) {
$.ajax({
url: "<%= spotify_search_path(:json) %>",
data: {
term: request.term
},
success: function (data) {
if (data.length == 0) {
data.push({
id: 0,
label: "No results found"
});
}
response(data);
}
});
},
select: function (event, ui) {
if (ui.item.id != 0) {
append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web);
$("#shop_search").val('');
}
}
});
You'll need to do some work on your template to get the "no results found" to display properly, but this should get you on the right track.

You can just check if item is null or 0.
If item is 0 or null append "No matches found" else append the item. That's basically the whole logic.

May be this helps
source: function( request, response ) {
$.getJSON( url, {
term: extractLast( request.term )
}, response )
.error(function() {
console.log("no results");
});
},

$( "#jsonNameSearch" ).autocomplete({
// This is the source of the autocomplete, in the success method if the
// length of the response is zero then highlight the field indicating no match.
source: function( request, response ) {
$.getJSON( 'jsonAutocomplete.ajax?dataType=drivers', {
term: request.term
}, response )
.success(function(data) {
(data.length == 0) ? $( "#jsonNameSearch" ).addClass('nomatch') : $( "#jsonNameSearch" ).removeClass('nomatch');
});
},
select: function( event, ui ) {
if (ui.item) self.location.replace('driverModify.htm?id='+ui.item.id);
}
});

Related

jquery UI Autocomplete with stored list

Hi I'm using jQuery UI Autocomplete and want do something like this: I want to get the list with AJAX when length=3 and this work great it populate the drop-down. Next I want when the length is >3 to use the returned list from the AJAX and filter it. But it give the same list not filtered.
$( ".selector" ).autocomplete({
source:function(request, response) {
var str_req = request.term;
if(str_req.length==3) {
$.ajax({
url: "/?search=1",
type: "GET",
dataType: "json",
data: {term: request.term},
success: function (data) {
auto_data=data;
response(data);
}
});
} else{
return response(auto_data);
}
},
minLength: 3,
select: function( event, ui ) {
console.log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
I would simply set the min to 1 and do a comparison in the source.
$(".selector").autocomplete({
source:function(request, response) {
var str_req = request.term;
if(str_req.length < 3) {
// Send your list back, if it was stored in 'myData'
response(myData);
} elseif(str_req.length==3) {
$.ajax({
url: "/?search=1",
type: "GET",
dataType: "json",
data: {term: str_req},
success: function (data) {
auto_data=data;
response(data);
}
});
} else{
response(auto_data);
}
}
},
minLength: 1,
select: function(event, ui) {
console.log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
You could also do this as a Switch statement:
var str_req = request.term;
switch(true){
case str_req.length < 3:
// Send your list
break;
case str_req.length == 3:
// Perform AJAX & return results
break;
default:
// All other options
response(auto_data);
}

jQuery UI Autocomplete on KeyPress write value

I am trying to implement jQuery UI Autocomplete the way like
when I have a list "alpha","beta","gamma" then type "a" into the input field
and only get "alpha" as proposal I want to hit enter and "alpha" shall be
the new value of the input field instead of selecting "alpha" by mouse click.
Is this possible?
$.ajax({
url : 'myAjax.php',
type : 'POST',
data : { param: getData },
dataType : 'json',
success : function(data) {
$("#myField").autocomplete({
minLength: 0,
source: data,
focus: function( event, ui ) {
$(this).val(ui.item.key);
return false;
},
select: function( event, ui ) {
$("#myField").val(ui.item.value);
return false;
}
});
}
});
you can add
autoFocus: true
this will make it focus on the first element that you get
and when you press enter it will automatically put the label in the field by using
$("#myField").val(ui.item.label);
Yes it's possible, you have to put more parameter on your autocomplete method
$( "#tags" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( data, function( item ){
return matcher.test( item.label );
}) );
},
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$("#tags").val(ui.item.label);
$("#selected-tag").val(ui.item.label);
window.location.href = ui.item.value;
}
,
focus: function(event, ui) {
event.preventDefault();
$("#tags").val(ui.item.label);
}
});
see this exemple link

jquery ui autocomplete with autoselect plugin

I am using a jquery ui autocomplete. when the user types in their own value, rather than selecting an item from the list, the textbox clears. This is ok (I don't want the user to be able to enter their own values) except if the user types in a value that does exist on the list.
I tried using the autoSelect plugin as detailed in this post, but it is not working - I added the plugin but when I type in a value that IS on the list and hit tab, I get the same results as before - the textbox clears.
Here is my autocomplete:
$(function () {
$('[id$="txtDocType').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/MyPage.aspx/myFunction",
data: "{'prefixText':'" + request.term.toLowerCase() + "', 'ddvId':'" + this.element.data('autocomplete') + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) { }
});
},
minlength: 1,
select: function (event, ui) {
$('#divOtherFields input[type=text], input[type=password]').prop("disabled", false).removeClass("disabled");
$('[id$="btnSaveNext"],[id$="btnSaveClose"]').prop("disabled", false);
$('[id$="txtReceiptDate"]').datepicker("setDate", new Date());
}
});
});
Here is the plugin:
(function( $ ) {
$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).on( "blur", function( event ) {
var autocomplete = $( this ).data( "autocomplete" );
if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
autocomplete.widget().children( ".ui-menu-item" ).each(function() {
var item = $( this ).data( "item.autocomplete" );
if ( matcher.test( item.label || item.value || item ) ) {
autocomplete.selectedItem = item;
return false;
}
});
if ( autocomplete.selectedItem ) {
autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
}
});
}( jQuery ));
I set a breakpoint in the plugin on this line - "$( ".ui-autocomplete-input" ).on( "blur", function( event )" and the breakpoint was hit, yet the code would not step through. When I set a breakpoint to this line - "var autocomplete = $( this ).data( "autocomplete" );" the breakpoint was NOT hit.
Any ideas? I am at my wits end with this.
I solved this by making a couple of tweaks to the autoSelect plugin. Here is the code that eventually worked for me:
$(".ui-autocomplete-input").bind("focusout", function (event) {
var autocomplete = $(this).data("ui-autocomplete");
if (!autocomplete.options.autoSelect || autocomplete.selectedItem) { return; }
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
autocomplete.widget().children(".ui-menu-item").each(function () {
var item = $(this).data("ui-autocomplete-item");
if (matcher.test(item.label || item.value || item)) {
autocomplete.selectedItem = item;
return false;
}
});
if (autocomplete.selectedItem) {
autocomplete._trigger("select", event, { item: autocomplete.selectedItem });
}
});
I used the focus event to set the first value to a hidden variable. The same hidden variable also got updated in the select event. And then this was the hidden variable which I posted to the ajax call.
Why I did not use focus to set the value in the autocomplete input box, was because doing so populated the autocomplete input box even while I was typing in this box.
focus: function (event, ui) {
if($("#streetid")) $("#streetid").val(ui.item.label); //this was my hidden variable
}
},

jquery autocomplete renderItem

I have the following code. It generates no js errors. Can't get the autocomplete to display any results:
$(function() {
$.ajax({
url: "data.xml",
dataType: "xml",
cache: false,
success: function (xmlResponse) {
var data_results = $("Entry", xmlResponse).map(function () {
return {
var1: $.trim($("Partno", this).text()),
var2: $.trim($("Description", this).text()),
var3: $.trim($("SapCode", this).text()),
var4: $("Title", this).text(),
var5: $.trim($("File", this).text()),
var6: $.trim($("ItemID", this).text())
};
}).get();
$("#searchresults").autocomplete({
source: data_results,
minLength: 3,
select: function (event, ui) {
...
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" ).data("item.autocomplete", item)
.append( "<a>" + item.var1 + "<br>" + item.var2 + "</a>")
.appendTo( ul );
};
}
});
Any ideas what I might be missing? Thanks in advance.
It seems that .data('autocomplete') is now .data('ui-autocomplete').
Source: http://jqueryui.com/upgrade-guide/1.10/#removed-data-fallbacks-for-widget-names
By default, autocomplete expects your source array to contain objects with either a label property, a value property, or both.
With that in mind you have two options:
Add a label or value property to your source objects when you process the array from your AJAX call:
var data_results = $("Entry", xmlResponse).map(function () {
return {
var1: $.trim($("Partno", this).text()),
var2: $.trim($("Description", this).text()),
var3: $.trim($("SapCode", this).text()),
var4: $("Title", this).text(),
var5: $.trim($("File", this).text()),
var6: $.trim($("ItemID", this).text()),
value: $.trim($("Description", this).text())
};
}).get();
The value you assign will be used on focus, select, and to search on.
Change the source function to perform custom filtering logic:
$("#searchresults").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(data, function (value) {
return matcher.test(value.var1) ||
matcher.test(value.var2);
/* etc., continue with whatever parts of the object you want */
}));
},
minLength: 3,
select: function (event, ui) {
event.preventDefault();
this.value = ui.var1 + ui.var2;
},
focus: function (event, ui) {
event.preventDefault();
this.value = ui.var1 + ui.var2;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" ).data("item.autocomplete", item)
.append( "<a>" + item.var1 + "<br>" + item.var2 + "</a>")
.appendTo( ul );
};
Note that with this strategy you have to implement custom select and focus logic.

add image to jQuery UI autocomplete remote source with cache

I am using jQuery autocomplete remote source with caching. As per demo by jQUery UI website javascript of remote source with caching is
<script>
$(function() {
var cache = {},
lastXhr;
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
});
</script>
Now I want to add some code to above javascript to display image in autocomplete list. There is an excellent example for displaying image in jQuery autocomplete such as:
http://jsfiddle.net/3zSMG/ but it does not include caching part.
I have been trying but NOT able to integrate this example into the existing remote with caching javascript. Any help would be very much appreciated. Many thanks.
FOLLOW-UP: As suggested by Andrew Whitaker, I have updated my script as follow:
<script>
$(function() {
var cache = {},
lastXhr;
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response(cache[term]);
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
var results;
if ( xhr === lastXhr ) {
results = $.map(data, function(item) {
return {
value: item.value,
avatar: item.avatar
};
});
cache[term] = results;
response(results);
}
});
},
}).data("autocomplete")._renderItem = function (ul, item) {
if ( item.value != null ) {
if ( item.avatar != null) {
return $("<li/>")
.data("item.autocomplete", item)
.append("<a><img src='images/" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
}
else {
return $("<li/>")
.data("item.autocomplete", item)
.append("<a>" + item.value + "</a>")
.appendTo(ul);
}
}
};
});
And content of search.php:
<?php
require_once "config.php";
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "select id, subject as value, avatar from Suggests where subject LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row['avatar']=$row['avatar'];
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
?>
I am able to see images in autocomplete list. But there is an issue: After keying in few letters, autocomplete list is shown up, if I continue adding some more random letters to expect autcomplete list to disappear (because the userinput no longer matches) but it does not. Andrew's example work well. Is there anything wrong with my javascript? Trying to debug by Firebug, I got error: TypeError element is null.
The key to the image portion of the demos is overriding the _renderItem function to change the li's that are generated to suggest items. This usually means that your source is an array with objects that have a label and/or value property, as well as a property that allows you to display the image correctly inside of _renderItem.
The caching code just stores the search term and results in a hash and looks in that hash before hitting the server.
Using the JSFiddle you linked as an example, here's something using StackOverflow's API that does caching and images:
$(document).ready(function() {
var cache = {},
lastXhr;
$("#auto").autocomplete({
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.ajax({
url: "http://api.stackoverflow.com/1.1/users",
data: {
filter: request.term,
pagesize: 10
},
jsonp: "jsonp",
dataType: "jsonp",
success: function(data, status, xhr) {
var results;
if (xhr === lastXhr) {
results = $.map(data.users, function(el, index) {
return {
value: el.display_name,
avatar: "http://www.gravatar.com/avatar/" + el.email_hash
};
});
cache[term] = results;
response(results);
}
}
});
},
delay: 500
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
};
});​
Notes:
This example is more complex than the examples on jQueryUI's website because the data from the API has to be transformed (to have avatar/value properties). The important thing to note is that we're caching the received values after the $.map call transforms the result array.
This looks complicated but just remember the two guidelines at the top of the answer and you should be good.
Example: http://jsfiddle.net/rK7TS/
Here's what I did:
lastXhr = $.getJSON( action, request, function( data, status, xhr ) {
if( data && data !== null ) {
var results;
if( xhr === lastXhr ) {
results = $.map(data, function(item) {
return {
value: item.value,
avatar: item.avatar
};
});
cache[term] = results;
response(results);
}
} else {
response([{ value: 'No results found.', avatar: null}]);
}
});

Resources