JQuery autocomplete Search method - javascript

I am using JQuery UI autocomplete on my website. I am creating the auto complete object like so:
$.widget( "custom.code_complete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this,
currentCategory = "";
$ul = ul;
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
self._renderItem( ul, item );
});
}
});
$("#r-code").code_complete({
source: "URL",
minLength: 2,
select: function(event, ui) {
$(".button-row").fadeIn();
get_details(ui.item.url);
}
});
This setups the autocomplete field fine. I can search inside the field fine and it brings back results without a problem. Sometimes however the users will be redirected from another page with the autocomplete value set as a parameter and if this is the case the autocomplete will be triggered programmatically, I am trying to do this with the following code:
function parse_param_code(code) {
console.log(code);
$("#r-code").autocomplete('search', code);
}
This method is called successfully and the code is put out to the console but the autocomplete search is not triggered and does not do anything. Am I doing something wrong in my code for this not to trigger a search? I have read the JQuery UI documentation and the above code is supposed to trigger the search method. Any help would be appreciated.
Thanks
Eef

Changing the
$("#r-code").autocomplete('search', code);
to your own widget name, i.e:
$("#r-code").code_complete('search', code);
produces the desired result.
example: http://jsfiddle.net/vHJsu/
If you do a console.log($("#r-code").data("autocomplete")); you'll notice there isn't a widget with that name attached to the element.

Related

appendTo custom element not updating with autocomplete

I have a search box and am using Jquery autocomplete to get the search results which I want to return to a custom element.
At the moment it appends every time the search changes which leads to duplicates.
I was wondering if there is an option which will delete the contents of the custom element when the search term changes.
var $searchFriends = $("#searchFriends");
$searchFriends.autocomplete({
source: "search/findFriends",
minLength: 3,
appendTo: "#searchResults",
select: function(event, ui) {
$('#searchFriends').val(ui.item.value);
return false;
}
})
.data("uiAutocomplete")._renderItem = function( ul, item){
return $("<li class='friendResult' id='"+item.id+"'>")
.append("<a>"+item.value+"</a>")
.appendTo('#searchResults')
};
I currently have a work around which is working fine (below) but there must be another way.
$searchFriends.on('change textInput input', function (){
$('#searchResults').empty();
});
You can use html() to replace the html in an element (instead of using append() to append it).
var $searchFriends = $("#searchFriends");
$searchFriends.autocomplete({
source: "search/findFriends",
minLength: 3,
appendTo: "#searchResults",
select: function(event, ui) {
$('#searchFriends').val(ui.item.value);
return false;
}
})
.data("uiAutocomplete")._renderItem = function( ul, item){
var content = $("<li class='friendResult' id='"+item.id+"'>").append("<a>"+item.value+"</a>");
$('#searchResults').html(content);
};

javascript search functionality

I got an autocomplete search bar displaying the dropdown menu with images and text which is working good, but the problem is when there are no search results to display, the "No results found" text is also displaying with an image (like the actual results) and I know it is due to my _renderItem() method in jquery. I don't want it to display like that, but I just want the plain text saying "No results found"
I have been trying to figure it out but was unable to. Any help is much appreciated. Thanks.
This is javascript for displaying "no results found" (just the relevant part of code)
success: function( data ) {
if (data.length === 0) {
data.push ({
id: 0,
label: "No results found"
});
}
response( $.map( data, function( item ) {
return {
label: item.label,
id: item.id
};
}));
And this is _renderItem()
.data('autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.data('item.autocomplete', item)
.append("<a>"+"<img src ='/account/"+item.id+"/icon/logo' width='40' height='40'/>" + item.label+"</a>")
.appendTo(ul);
};
And this is select() event
select: function( event, ui ) {
window.location="/account/" + ui.item.id;
return false;
}
How do I modify these two function in order to display just "No results found" text.
I have tried using if (data.length > 0) {} but it doesn't seem to be working.
Since your only concern is of image, you can try something like this:
append("<a>"+"<img src ='/account/"+item.id+"/icon/logo' onerror='$(this).hide()' width='40' height='40'/>" + item.label+"</a>")
Adding an error attribute which hides the image on error. Since on no results found, you'll have a broken image which you easily hide using:
onerror="$(this).hide()"

jquery autocomplete with different sources

I hope you can help me. I'm looking for a possibility to make my jquery autocompleter use a different source whether the first input is a digit or a letter (on the fly). I tried days and could not make it working.
Thats the autocomplete code:
$(function() {
$("#ac1").autocomplete(
'search.php', //or blub.php
{onItemSelect: function(item) {
var text = 'test';
$("#num1").val(item.data);
var selector = $("#num1").val();
var additionalradius = selector.substring(0,3);
var zip = selector.substring(6);
$("#num1").val(additionalradius);
$("#3rd").val(zip);
alert (additionalradius);
}},
{selectFirst: true}
);
});
So I need something like "if first key in field #ac1 is a number, then use search.php. Else use blub.php" in that code shown. Any idea? Thank you for you help.
To set the source option in search event ( that is triggered before a search is performed ) is one way to do it.
$("#ac1").autocomplete({
source: 'search.php',
search: function( event, ui ) {
if ( isNaN( parseInt( $(this).val().charAt(0) ) ) )
$(this).autocomplete( 'option', 'source', 'blub.php' );
else
$(this).autocomplete( 'option', 'source', 'search.php' );
}
});
EDIT:
$("#ac1").autocomplete({
source: 'search.php',
search: function( event, ui ) { /* code from search function here */ },
select: function( event, ui ) { /* code for item select here */ }
/* additional options */
});

Jquery UI Autocomplete List does not refresh

So I am using jquery ui autocomplete where the list that is displayed is fetched via WebSockets. A call to fetch the list is made on every keystroke on the input field(.keyup()). Problem is that once I type in a character and a corresponding list is fetched and displayed, the next keystroke searches for the search parameter in the input field within the previous list instead of the new one that was fetched. To get the new options I need to press backspace. For example, if I enter "S" on the input, results corresponding to "S" will be fetched and displayed. If I further enter "h", making the search term "sh", then the list corresponding to "sh" is fetched, but the autocomplete searches for "sh" within the previous list. Simply put the list does not get refreshed immediately. How can I get the list to refresh immediately? Thanks in advance for any help.
UPDATE: So here's a bit of the code:
This is the part where the keystroke is detected and the search initiated
$('#pick_up_location').keyup(function(e) {
var param = $("#pick_up_location").val();
var userType = "1";
search(param, userType,"CBPickSearchAction", "", 0);
This is where the results received are displayed in autocomplete:
function onMessage(data) {
try
{
var obj = $.parseJSON(data);
$("#pick_up_location").autocomplete({
source: obj,
minLength: 0,
delay: 0,
autoFocus: true,
search : function() {
},
//open : function(){$(this).removeClass('working'); $(".ui-autocomplete").width($(this).width());},
focus: function( event, ui ) {
event.preventDefault();
return false;
},
open : function(event, ui){
$('#pick_up_location').autocomplete("widget").width();
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$("#pick_up_location").autocomplete('enable');
$("#pick_up_location").keydown();
} catch(err)
{
//console.log( err.message);
}
So finally I found a solution. The problem was that usually when retrieving a list for autocomplete from another domain, an ajax call is made to return results to the source. However, since my goal was to make this commercial application whilst substituting all ajax calls with the use of websockets, the autocomplete wasn't working as desired. Also, I had restricted myself to making all API calls with just a single websocket opened.
All I had to do was to make a new connection in javascript to the websocket in Java and use its onmessage function to receive the results and place them in the response of the autocomplete. Previously, the autocomplete's source was a var that contained the results when they had been returned. But this was not exactly working as desired because on every keystroke it just searched through the results already there. You would have to enter backspace for the list to refresh.
Here's the modified code snippet:
function locationSearch() {
$("#pick_up_location").autocomplete({
source: function(request,response) {
var action = "CBPickSearchAction";
var userType = 1;
var requestString = createRequestStringForLocationSearch(action, userType, request.term);
webSocket_local.send(requestString);
webSocket_local.onmessage = function(event) {
data = event;
data = formatLocationResponse(data, action);
response($.parseJSON(data));
};
},
minLength: 0,
delay: 0,
autoFocus: true,
focus: function( event, ui ) {
event.preventDefault();
return false;
},
open : function(event, ui){
$('#pick_up_location').autocomplete("widget").width();
},
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
}
$('#pick_up_location').keyup(function(e) {
locationSearch();
}
Thus my goal to create an ajax-free web application was accomplished. :)
If anyone has an even better solution, I'd be interested in knowing.

Autocomplete with Categories and remote datasource

What I want to do is have categorised results using autocomplete through jQueryUI's function. After some googling etc I found that it has an inbuilt function (http://jqueryui.com/demos/autocomplete/#categories) but the example is only for a local data source (an array in javascript). I am dealing with a remote data source. The autocomplete side of it works fine without the categories code added in but breaks when it is added.
This means that the php code is fine (the search page that returns json data).
I took this code from the jQueryUI site:
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
self._renderItem( ul, item );
});
I then combined it with the search side of it (changing to category):
$(function() {
$( "#search" ).catcomplete({
delay:0,
source: "query/encode-json.php?term="+ $("#search").val(),
select: function(event, ui){
alert(ui.item.label);
}
});
});
But it does not work :( I've googled a lot but everyone else was having issues with the json side of it. Here's my json data:
[{"value":"some dude","id":"1","category":"artist"},{"value":"some other dude","id":"2","category":"artist"}]
I'm pretty sure your problem is the source property of the options object you're passing to autocomplete:
$("#search").catcomplete({
delay:0,
source: "query/encode-json.php?term="+ $("#search").val(),
select: function(event, ui){
alert(ui.item.label);
}
});
source will be evaluated once when you instantiate the widget. In other words, $("#search").val() does not get executed every time the user types.
Since by default autocomplete sends up term in the query string, you should just be able to do:
$("#search").catcomplete({
delay:0,
source: "query/encode-json.php",
select: function(event, ui){
alert(ui.item.label);
}
});
I'm pretty sure everything else is correct, since using your array as a local data source with categories works fine: http://jsfiddle.net/jadPP/
Use this:
http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/
(Updated)
Hope this helps :-)
The default _renderItem() method looks for item.label, but your json data contains item.value. You need to change your encode-json.php script to use label instead of value, or you'll have to use the version of source: where you provide your own callback function.

Categories