Using jQuery-ui autocomplete variables in further jQuery-ui autocomplete functions - javascript

How can I use the selected item from a jQuery-ui autocomplete in a further jQuery-ui autocomplete function?
e.g. for this HTML:
<div class="ui-widget">
<label for="project">Project: </label>
<input id="project" />
<label for="phase">Phase: </label>
<input id="phase" />
<label for="filename">Project: </label>
<input id="filename" />
</div>
I am using the following autocomplete function with a JSON endpoint to supply the data.
$(function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: function( event, ui ) {
}
});
});
Then in this second autocomplete I want to take the selected value from the first autocomplete function and use it to build the URL string for use in the source attribute of a second autocomplete (shown here as valueFromFirstAutocomplete).
$(function() {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+valueFromFirstAutocomplete,
minLength: 2,
select: function( event, ui ) {
}
});
});

Customize the source option with a callback, adding the additonal parameter to the URL:
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2
});
$( "#phase" ).autocomplete({
source: function(request, response) {
$.get(baseUrl + "/json/listphases/" + $("#project").val(), request, response);
},
minLength: 2
});

You could just put one inside the other....
Is there some reason this won't work?
$(function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: function( event, ui ) {
$(function() {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+ui.item.value,
minLength: 2,
select: function( event, ui ) {
}
});
});
}
});
});
To use these independently you could do something like this:
var funclist = {
populate1 : function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: populate2;
},
populate2 : function(event,ui) {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+ui.item.value,
minLength: 2,
select: populate3;
}
populate3 : ; // etc
}
$(funclist.populate1);

Related

jQuery UI Autocomplete value not appear properly in selection

My sources are JSON objects that fetched from url and it looks like below.
[
{"ID":1,"GROUP_ID":"1","CONTACTNAME":"Mizuki","PHONENUMBER":"+6289695049930"},
{"ID":15,"GROUP_ID":"3","CONTACTNAME":"Sinbad","PHONENUMBER":"+6287654321"},
{"ID":23,"GROUP_ID":"","CONTACTNAME":"Titus","PHONENUMBER":"+6255555555"}
];
When user typing, result of suggestion is CONTACTNAME and value that inserted into searchbox is PHONENUMBER. Fetch data from source/url have no issue but in searchbox there's no value passed.
Screenshot below
Here's my script
$(function() {
$( "#contact" ).autocomplete({
source: "api/contact/auto",
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
});
});
Form view
<input type="text" v-model="message.DESTINATIONNUMBER" id="tags" class="form-control" name="destinationNumber" >
I try to remove vue snippet (v-model) still same.
Any suggestion? Whats wrong?
UPDATED!!
My mistake. Forgot add this code at the end.
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
So, full javascript is like in jquery-ui docs
$(function() {
$( "#contact" ).autocomplete({
source: "api/contact/auto",
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
Thanks for people who try to help me. Appreciate it.
For the autocomplete to work, you need to have "label" attribute in the returned JSON array. You can either change that on the server side, or transform it on the client as follows:
$( "#contact" ).autocomplete({
source: function (request, response) {
$.ajax({
url: "api/contact/auto",
data: { query: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.CONTACTNAME,
value: el.PHONENUMBER,
id: el.ID
};
});
response(transformed);
},
error: function () {
response([]);
}
});
});
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
});
There were a couple of errors in your JavaScript:
"source" is misspelled ("sorGce")
in availableTags indexes except 0, the colon is inside the quotes instead of outside
Working fiddle:
sorGce: availableTags, -> source: availableTags,
"ID:" "23", -> "ID": "23",
https://jsfiddle.net/ep1s9w3s/1/
Not sure if this is the root cause of your problem or not, but it might help you fix your fiddle.

Cant push autocomplete selected value to global array in JavaScript

Im working on a project in which I have autocomplete with users list.
when I try to push autocomplete selected value to global array I get an empty list when I do console.info(usernames) outside autocomplete function.
var usernames=[];
$(document).ready(function(){
$(function(){
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "getUserFromDb.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event,ui){
usernames.push(ui.item.value);
}
});
console.info(usernames);
});
});
soruce of autocomplete is returning correct list and select works as well, because if I do console.info(usernames) inside autocomplete select: the list will update when im selecting different values.
Since you needed an "answer", here we go. First off, your console.info has run as soon as the DOM is ready and obviously empty as the user names are pushed in later on, when you select options from autocomplete. Secondly, you are not re-logging usernames as and when it's populated. So, you have 2 options.
1) log usernames within the select function, such as:
select: function(event,ui) {
usernames.push(ui.item.value);
console.info(usernames);
}
2) Have a function that would do the job for you, such as:
select: function(event,ui) {
usernames.push(ui.item.value);
showMeUserNames();
}
function showMeUserNames() {
console.info(usernames);
}
So, your code may become:
var usernames=[];
$(function(){
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "getUserFromDb.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event,ui) {
usernames.push(ui.item.value);
console.info(usernames);
// OR
// showMeUserNames();
}
});
});
function showMeUserNames() {
console.info(usernames);
}

How to apply jQuery auto-complete in a Form-Set?

I'm stick at my thinking on how to apply a JS code to a form-set.
I've this HTML:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input">
And I use this JS/jQuery code to auto-complete the #id_form-0-city_input input.
// Autocomplete stuff
$( "#id_form-0-city_input" ).autocomplete({ // mudar!!!!
source: function( request, response ) {
$.ajax({
url: "/internalapi/cidades/",
dataType: "json",
data: {
country: $('#id_country').find(":selected").val(),
term: request.term.toLowerCase()
},
success: function( data ) {
response($.map(data, function( item ) {
return {
label: item.name + " (" + item.zone + ", " + item.municipality + ")",
value: item.name,
id: item.id
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
var selectedObj = ui.item;
// Popular o campo id_city
$( "#id_form-0-city" ).val(selectedObj.id);
},
search: function(event, ui) {
$("#id_form-0-city_input").addClass( "ui-autocomplete-loading" ); // mudar!!!!!
},
open: function() {
$("#id_form-0-city_input").removeClass( "ui-autocomplete-loading" ); // mudar!!!!
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The code above works great, but now I need to use this auto-complete code for this case:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input">
<input id="id_form-1-city" name="id_form-0-city" type="hidden">
<input id="id_form-1-city_input" name="id_form-0-city_input">
<input id="id_form-2-city" name="id_form-0-city" type="hidden">
<input id="id_form-2-city_input" name="id_form-0-city_input">
<input id="id_form-3-city" name="id_form-0-city" type="hidden">
<input id="id_form-3-city_input" name="id_form-0-city_input">
<input id="id_form-4-city" name="id_form-0-city" type="hidden">
<input id="id_form-4-city_input" name="id_form-0-city_input">
...
...
The number of sets could be minimum 1 and maximum 10.
Can you give me some ideas to refactor the JS/jQuery code to work with formsets? A for loop is what I need to use?
You could add a rel element to your inputs if you don't want to use class, like:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-1-city" name="id_form-0-city" type="hidden">
<input id="id_form-1-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-2-city" name="id_form-0-city" type="hidden">
<input id="id_form-2-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-3-city" name="id_form-0-city" type="hidden">
<input id="id_form-3-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-4-city" name="id_form-0-city" type="hidden">
<input id="id_form-4-city_input" name="id_form-0-city_input" rel="autocomplete">
And then just add the autocomplete logic inside this
$("input[rel='autocomplete']").autocomplete({ // mudar!!!!
...
Just use a for loop...
var inputLength = $('input:not(input[type="hidden"])').length; //find non-hidden inputs
for(var a = 0; a<inputLength; a++){
// Autocomplete stuff
$( "#id_form-" + a + "-city_input" ).autocomplete({ // mudar!!!!
source: function( request, response ) {
$.ajax({
url: "/internalapi/cidades/",
dataType: "json",
data: {
country: $('#id_country').find(":selected").val(),
term: request.term.toLowerCase()
},
success: function( data ) {
response($.map(data, function( item ) {
return {
label: item.name + " (" + item.zone + ", " + item.municipality + ")",
value: item.name,
id: item.id
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
var selectedObj = ui.item;
// Popular o campo id_city
$( "#id_form-" + a + "-city" ).val(selectedObj.id);
},
search: function(event, ui) {
$("#id_form-" + a + "-city_input").addClass( "ui-autocomplete-loading" ); // mudar!!!!!
},
open: function() {
$("#id_form-" + a + "-city_input").removeClass( "ui-autocomplete-loading" ); // mudar!!!!
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
}
DEMO:
http://jsfiddle.net/NcTpj/10/

jQuery UI .autocomplete()

I have autocomplete working on my site with the following:
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
}
});
});
What I want to do now is that when a user types in something that is not shown on the dropdown, I'd like for the following to take place:
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
I tried using the following but it didn't work:
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
if(typeof(ui.item)){
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
} else {
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
}
}
});
});
the select evevnt is only triggered when you select an item in dropdown
you could do it on search event
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
},
search: function() {
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
}
});
});
I don't know what the whole idea is without seeing markup. But my guess is:
$("#client").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/appointments/clients.json",
dataType: "jsonp",
success: function( data ) {
var suggestions = $.map( data, function( item ) {
return {
label: item.value,
value: item.id
}
});
// idea: whatever I have, extend to extra item.
suggestions.push({
label: 'Add appointment',
value: 0
});
response( suggestions );
}
});
},
select: function(evt, ui){
if( ui.item.label == 'Add appointment'){
/* do something special with it */
}else{
/* blah blah */
}
}
});

jQueryUI Autocomplete - blur field after selection

I would like to be able to blur the field after I select a value from the dropdown. I currently have the autocomplete item searching on focus.
Here is what I have:
$("#season").autocomplete({
source: function( request, response ) {
$.getJSON( "search.asp", {
term: request.term,
type: 'season'
}, response );},
minLength: 0
}).focus(function(event, ui){
$(this).autocomplete("search","");
});
You could use the 'close' method to call blur on the input field:
$("#season").autocomplete({
source: function(request, response){
$.getJSON("search.asp", {
term: request.term,
type: 'season'
}, response);
},
minLength: 0,
close: function(){
$(this).blur();
}}).focus(function(event, ui){
$(this).autocomplete("search", "");
});
Autocomplete has a select event, which is triggered when you select something from the dropdown list. In that event you can call .autocomplete('close') on your input to close the dropdown.
$("#season").autocomplete({
source: function(request, response){
$.getJSON("search.asp", {
term: request.term,
type: 'season'
}, response);
},
minLength: 0,
select: function(){
$(this).autocomplete('close');
}
}).focus(function(event, ui){
$(this).autocomplete("search", "");
});
Familiarizing yourself with the docs does wonders :)
http://jqueryui.com/demos/autocomplete/
The tabs below the example (options, events, methods, etc.), will give you all you need to know.
EDIT:
Try this, works for me but I only tested in Chrome, FF3 and IE8.
$("#season").autocomplete({
source: function(request, response){
$.getJSON("search.asp", {
term: request.term,
type: 'season'
}, response);
},
minLength: 0,
select: function(){
$('#season').autocomplete('close').blur();
}
}).click(function(event, ui){
$(this).autocomplete("search", "");
});
Typically, using click instead of focus isn't a great idea.
Found the solution for me. You have to trigger the blur and close on the "change".
$("#season").autocomplete({
source: function( request, response ) {
$.getJSON( "search.asp", {
term: request.term,
type: 'season'
}, response );},
minLength: 0,
change: function (event, ui) {
$(this).autocomplete('close').blur();
}
}).focus(function(event, ui){
$(this).autocomplete("search","");
});

Categories