Autocomplete search box with initial values OnFocus - javascript

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

Related

Make jquery autocomplete common

I have an MVC - C# app with jquery autocomplete feature for some text boxes. Each View has autocomplete code, some are for the same field (different views), and some different fields as well.
ex.
Invoice\Create View customer text box
Payment\Create View customer text box
Payment\Create View Invoice Number text box
having autocomplete feature. All working as expected.
Here is a sample code (which is in each view for each control - this is for Customer)
$(document).ready(function () {
$("#CustomerName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetCustomers", "Invoices")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.CustomerName,
value: val.CustomerName,
CustomerId: val.CustomerId
}
}))
}
})
},
select: function (event, ui) {
$("#CustomerId").val(ui.item.CustomerId);
}
});
});
Now what I want is, create a common function in a file in Scripts Folder and call that, along with parameters, whenever I need this autocomplete feature to any control in any view.Is there a way to achieve it?
I tried the $(document).ready function in the view's script section, and few other options, but was unsuccessful.
Please let me know, at least whether this could be done or not
function (elementId,controllerName,actionName,fieldName) {
$("#"+elementId+"").autocomplete({
source: function (request, response) {
$.ajax({
url: 'api/'+controllerName+'/'+actionName+'',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val[0],
value: val[1],
fieldName: val.fieldId
}
}))
}
})
},
select: function (event, ui) {
$("#"+elementId+"").val(ui.item.fieldName);
}
});
}

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 ?
});

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

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 push the fetched autocomplete data from JSON API to a text box?

I am trying to fetch the values as Autocomplete jQuery method and store the selected input values into a text box (push to text box). Sounds easy but this JSON schema is kinda taking buzzy time.
Can I get a quick help here?
http://jsfiddle.net/ebPCq/1/
jQuery Code:
$("#material_number").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "json",
data: {
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.geonames, function (item) {
return {
// following property gets displayed in drop down
label: item.name + ", " + item.countryName,
// following property gets entered in the textbox
value: item.name,
// following property is added for our own use
my_description: item.fcodeName
}
}));
}
});
After fixing up and finalizing the initial functionality, I came upon conclusion with this fiddle as the solution to my query posted above.
http://jsfiddle.net/ebPCq/7/
JS Code:
$(function () {
$("#input").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "json",
data: {
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.geonames, function (item) {
return {
// following property gets displayed in drop down
label: item.name + ", " + item.countryName,
// following property gets entered in the textbox
value: item.name,
// following property is added for our own use
my_description: item.fcodeName
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
if (ui.item) {
$("#push-input").prepend(ui.item.value + '\r\n');
}
}
});
});

Categories