This is my current code:
var areaid;
$( "#FindCentre" ).autocomplete({
//Doesn't give the right value here.
source: "databasescripts/findcentre.php?AreaID=" + areaid,
minLength: 2,
select: function( event, ui ) {
},
html: true,
});
$( "#FindArea" ).autocomplete({
source: "databasescripts/findarea.php",
minLength: 2,
select: function( event, ui ) {
areaid = ui.item.id;
alert(areaid);
//Alerts the correct value here.
},
html: true,
});
When users type into FindArea it alerts the correct value, however when they then type into FindCentre it will always come back as being undefined. I've tried reading the ID from FindArea in FindCentre but I can't seem to do that either.
Does anyone have any suggestions?
When you make the first autocomplete call, it sets up the autocomplete with the static value, i.e. areaid = undefined. If you want to use autocomplete with dynamic value you need to do something like this:
source: function(request, response) {
$.ajax({
url: "databasescripts/findcentre.php?AreaID=" + areaid //or + $("#FindArea").val()
});
}
Related
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)
This error: "Uncaught TypeError: string is not a function" is returning on an Ajax call I'm trying to do.
The code is:
$('input.js-nome-produto-servico').live("keyup", function(ed, h){
var $campo = ed.currentTarget;
$campo.autocomplete({
source: "<%=Rails.application.routes.url_helpers.busca_todos_produtos_servicos_por_nome_comercial_produto_servico_oportunidades_path%>?nome="+$campo.value,
minLength: 2,
change: function(event, ui) {
bindLoadingAnimation();
},
select: function( event, ui ) {
preencheCamposCliente(campo);
}
});
});
The error is rising on $campo.autocomplete.
I know I should call something like:
$("#field-id").autocomplete({ .........
But I have several fields that must respond to the same "keyup" event on the same way and use the same class (js-nome-produto-servico).
So I tried to get the DOM object (an input) from the keyup function (ed). When I call the debugger, the variable $campo has the correct object, but autocomplete doesn't work.
I think I'm missing some JS/JQuery concepts here. Can anyone give me the correct way to do this?
Thank you very much!
Have you tried the "search" event? Like:
$('.your_class').autocomplete({
source: "<%=Rails.application.routes.url_helpers.busca_todos_produtos_servicos_por_nome_comercial_produto_servico_oportunidades_path%>?nome="+ $(this).val(),
//below I replace the Minlength
search: function(){
if ( $(this).val().length < 2 ) {
return false;
}
}
change: function(event, ui) {
bindLoadingAnimation();
},
select: function( event, ui ) {
preencheCamposCliente(campo);
}
});
See if it works?
If anyone face the same problem, the solution is to use $(this) tag. So the code would be:
$('input.js-nome-produto-servico').live("keyup", function(ed, h){
$(this).autocomplete({
source: "<%=Rails.application.routes.url_helpers.busca_todos_produtos_servicos_por_nome_comercial_produto_servico_oportunidades_path%>?nome="+$(this).val(),
minLength: 2,
change: function(event, ui) {
bindLoadingAnimation();
},
select: function( event, ui ) {
preencheCamposCliente($(this));
}
});});
$(this) is the object that was affected by the 'keyup' event.
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 */
});
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.
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.