jQueryUI Autocomplete - blur field after selection - javascript

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

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

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

Change event in Autocomplete jQuery

in my project im using the jQuery Autocomplete which is working great.
the problem is, that i want to handle a situation were a user changes the input of the text.
for ex. the data contains ("prov 1", "prov 2"), the user choose from the menu "prov 1" but then changed it to "prov 2" by changing the 1 with 2.
i implemented the "change" event in the js but the ui.item is empty (i guess since the menu is not shown..)
i read that the "change" event is fired only when the text box is losing focus -> not to good for me, since the flow is selecting a "prov" and clicking button to continue.
any suggestions ??
here is my code:
JS
$(element).autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Label,
value: item.Label,
realValue: item.Value
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-id');
$('#' + hiddenFieldName).val(ui.item.realValue);
hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.label);
},
change: function (event, ui) {
alert('changed');
if (!ui.item) {
alert('no value'); /* IS FIRED */
} else {
}
}
});
});
Try the keypress event handler -- http://api.jquery.com/keypress/
Try change this:
change: function (event, ui) {
to this:
input: function (event, ui) {
Or you can try with this:
$(element).autocomplete({
minLength: 2,
//all your code but not change: function
}).on('input', function(e){
alert('changed');
if (this.value.length <== 0) {
alert('no value'); /* IS FIRED */
} else {
alert(this.value);
}
});

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

Categories