jquery autocomplete with different sources - javascript

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 */
});

Related

Jquery autocomplete dropdown not working in dynamic build textbox

I have build a search textbox dynamically and i want to do autocomplete search . Below is my code,
function getEmp(){
$('#itemSearch').autocomplete({
"source":function(request, response) {
var textInput = document.getElementById('a');
textInput.value = textInput.value.replace(/^\s+/,"");
var jqxhr = $.getJSON( baseurl +'test/search-emp', {
cName :$("#a").val(),
},response);
jqxhr.success(function() {
});
},
"select":function(e, ui){
},
"minLength":1,"autoFill":true,"showHeader":true});
}
I got the ajax result,but dropdown is not visible in autocomplete search.Please provide a solution
according to document ; http://api.jqueryui.com/autocomplete/#option-source
Your ajax must return an array or like ...
[ { label: "Choice1", value: "value1" }, ... ]
Prepare an api or something return documented kind a data vie Get
this source must use 'term' parameter
then put this to page YOUR_AJAX_URL must point your api...
$( function() {
$("#itemSearch" ).autocomplete({
source: "YOUR_AJAX_URL",
minLength: 2,
select: function( event, ui ) {
alert(ui.item.value);
}
});
} );
ps. https://jqueryui.com/autocomplete/#remote at here you can investigate developer tools in chrome (or similar)

cant select value of jqGrid autocomplete

I use a jqGrid with jquery autocomplete on one column.
{
name : 'mdmKndcode',
index : 'mdmKndcode',
width : 150,
align : "center",
editable : true,
edittype: 'text',
editoptions: {
dataInit: function(elem) {
var cache = {};
$(elem).autocomplete({
source: function( request, response ) {
var term = request.term;
console.log(term);
if(term in cache){
response(cache[term]);
return
}
$.getJSON( "/example/json/"+term, request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
},
minLength:3
});
}
}
In the grid I can see the results of json request in autocomplete list. This works fine. But I am not able to select a value in this list. The autocomplete list getting closed and lose the focus of the column after a mouseover or Keyboard press on the list.
Tried also with "select" function but same result.
Want to have the selection of the values in the list like in this Demo
Looking at your jsfiddle, the problem is that you are including jqueryui twice jquery-ui.js and jquery-ui-custom.min.js , most likely both of them have autocomplete and that causes troubles.
Remove one of them and that will fix the issue.
See here

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.

JQuery autocomplete Search method

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.

Categories