Cant push autocomplete selected value to global array in JavaScript - 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);
}

Related

Javascript - Autocomplete on focus textfield

I have this code for autocomplete after another textfield has been compiled. Problem it is that this autocomplete works only after is inserted 1 letter, i want to show autocomplete when text field is focus. I tried put event focus too, but it doesn't do any call to server. How can i show autocomplete results when user just click/focus on textfield?
$("#localitaTextBox").autocomplete
({
source: function (request, responce) {
$.ajax({
url: '#Url.Action("GetAllLocalitaJson", "Spedizione")',
method: "post",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({ localita: request.term, cap: $("#capTextBox").val() }),
dataType: 'json',
success: function (data) {
responce($.map(data.Result, function (item)
{
return {
label: item.Localita + ", " + item.CAP,
value: item.Localita,
id: item.CAP,
};
}))
},
error: function (err) {
alert(err);
}
});
},
select: function (e, ui)
{
$("#capTextBox").val(ui.item.id);
compileProvCode();
code = compileStatoCode();
// compileNation(code);
},
});
You might need to pass an option minLenght as follow:
$( ".selector" ).autocomplete({
minLength: 0 // this one!
});
by default is 1 but I believe 0 will work for you.
I also believe that on focus shouldn't be making calls to the server just because when you make a call this will look for * (everything) without any restriction and can be a bad UX. good luck!
edit:
Try this, is a bit hacky and definitely shouldn't be this way but I think they have a bug? They are actually expecting a keypress down
$("#localitaTextBox").on("focus", function() {
$(this).autocomplete({
minLength: 0,
source: availableTags
});
$(this).trigger("keydown"); //magic line ?
});

Autocomplete search box with initial values OnFocus

I have the following autocomplete functionality integrated on www.swimstats.net:
$("#athleteName1").autocomplete({
minLength: 3,
delay: 300,
source: function (request, response) {
$.ajax({
type: "POST",
url: "/query_athletes",
data: { first: $('#athleteName1').val() },
success: response,
});
}
}).focus(function () {
console.log('Populate');
});
I am looking for a solution that presents the user up to 5 previously selected values when the input field #athleteName1 gets the focus. Aspired "OnFocus" Behavior . The advantage of it is that the user does not have to search again for the athletes he previously searched.
However, as soon as the user starts typing, autocomplete should take over again while the previously selected values disappear.
Any idea how to build a nice and clean solution to achieve that?
Not sure if this is the most elegant way, but it does the job:
$("#athleteName1").autocomplete({
minLength: 0,
delay: 300,
source: function (request, response) {
if ($( "#athleteName1" ).val().length == 0) {
response(['banana','apple', 'orange']);
return;
}
$.ajax({
type: "POST",
url: "/query_athletes",
data: { first: $('#athleteName1').val() },
success: response,
});
},
}).focus(function () {
if ($( "#athleteName1" ).val().length == 0) {
$( "#athleteName1" ).autocomplete("search");
return;
}
});

Javascript If statement not working in autocomplete

I have the following Javascript code that works perfectly as far as the autocompleting as well as filling 5 additional input fields, based on the loaded array from MySQL in the type_code.php file.
The sixth element of the array val(names[6]) is filled with a database value of either Yes or No and I am trying to use this value to control whether an additional form field becomes readonly or readwrite at the front end.
It seems as if my if statement is badly formatted, as if I run the two lines of codes without the if everything works as expected.
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if($(val(names[6])) == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
Can someone please help me structure this if statement correctly?
Thanks,
Adri
The val() method returns or sets the value attribute of the selected elements.
Note: The val() method is mostly used with HTML form elements.
Use
if(names[6] == "Yes")
instead of
if($(val(names[6])) == "Yes")
=========================================================================
<script type="text/javascript">
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if(names[6] == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
</script>
Need following change in your code
// Code that is not working
if(names[6] == "Yes") //Change this if($(val(names[6])) == "Yes")
{
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
}
else
{
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}

Display the name but submit the ID with jQuery tag-it

Thanks for your time reading and helping!
I'm using the jQuery "tag-it" plugin: https://github.com/aehlke/tag-it
I've already checked the current questions and answers on the site, but they didn't help to achieve the 100% of what I need. I need help with the last step.
What I'm trying to do is, when the user is writing an email address, the system suggests what users belong to that address.
The suggestions are generated in a PHP page and I take them using AJAX from the plugin. The format given is this:
[
{"value": "13", "label": "Mauricio"},
{"value": "4", "label": "Manolo"}
]
"value" is the ID of the user and "label", the name of the person.
In the example, "Manalo" and "Mauricio" are displayed as suggestions to select. But when they are selected, what is displayed is the ID of the user (the "value"), not the name (the "label").
What I want to do is to display the name of the selected users but when I send the form, only the IDs are sent.
This is the current code. Thanks a lot for the help again.
$(".users").tagit({
autocomplete: {
source: function(request, response) {
$.ajax({
type: "GET",
url: 'test_json.php?text=' + request.term,
dataType: "json",
success: function(data) {
response( $.map( data, function( item ) {
return {
label: item.label,
value: item.value
}
}));
}
});
},
},
});
Get the selected option value from the jquery Autocomplete
$(".users").tagit({
autocomplete: {
source: function(request, response) {
$.ajax({
type: "GET",
url: 'test_json.php?text=' + request.term,
dataType: "json",
success: function(data) {
response( $.map( data, function( item ) {
return {
label: item.label,
value: item.value
}
}));
},
select: function(event, ui) {
//For better understanding kindly alert the below commented code
var selectedObj = ui.item;
alert(selectedObj.value);
}
});
},
},
});

How to get the unique value in autocomplete in php from mysqldatabase

How to get the unique value in autocomplete in php from mysqldatabase. and how do i get all values just like i have 3 values in autocomplete which same so i want only one in autocomplete but want to fetch the data of all. how do i do this ?
just like in picture i want 1 one php only but want the data from all the three values.
i am trying some thing like this
var citycode;
$('#countryname_1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'country_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
var len=code.length;
var co= code[0];
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|").length;
var dat = ui.item.data.split("|");
citycode=dat[0] ;
alert(citycode);
}
});

Categories