Javascript - Autocomplete on focus textfield - javascript

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

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

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

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

Return data for first key stroke undefined in jQuery autocomplete

I am trying to implement jQuery autocomplete using the approach illustrated below (i.e. a separate source function and an intermediary variable for the data). Right now I'm trying to get the data to the source part of the autoComplete function.
The code below works with one fatal issue, the very first key stroke returns an undefined returnData variable. Can any one explain what's going on?
var returnData;
function sourceFn() {
return $.ajax({
url: //REST URL,
dataType: "jsonp",
async: false,
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
returnData = data;
},
})
}
}
$("input#search-input").bind("autocompleteselect", jQuery.proxy(function (event, ui) {}, this)).autocomplete({
appendTo: "#yt-result-list",
source: function (request, response) {
sourceFn(request, response).done(alert("returnData: " + JSON.stringify(returnData)));
}
}).data("autocomplete")._renderItem = jQuery.proxy(function (ul, item) {
alert(item);
}, this)
});
});
});
Try specifing the minLength: 0 when initializing the autocomplete, check the value of returnData to see if you get the json back from the server (use firebug).
Looks like you're not getting from the ajax call with one letter only, the autocomplete is triggering sourceFn() correctly.

Can the default "Term" name passed in the "jquery UI autocomplete" feature be changed?

I am trying to change the "term" field that is set to that by default with the jquery ui autocomplete feature. Is it possibly to easily change it to "q" (query) without going and changing it in the "core" file?
JavaScript:
<script>
$(function() {
$( "#spotify_song_search" ).autocomplete({
source: "http://ws.spotify.com/search/1/track.json",
data: {
q: request.term
},
dataType: "getjson",
minLength: 3,
select: function( event, ui ) {
alert('select');
}
});
});
</script>
Yes, it's possible by making your own AJAX request.
Assume you have the following setup:
$("#myfield").autocomplete({
source: '/my_url/myservice.xyz'
});
Autocomplete by default (as you noticed) sends requests that look like:
myservice.xyz?term=abc"
You can supply a function reference to the source option of autocomplete. Inside that function you can make your own AJAX request, which would look like this:
$("#myfield").autocomplete({
source: function (request, response) {
// request.term is the term searched for.
// response is the callback function you must call to update the autocomplete's
// suggestion list.
$.ajax({
url: "/my_url/myservice.xyz",
data: { q: request.term },
dataType: "json",
success: response,
error: function () {
response([]);
}
});
});
});
This should generate a request looking more like:
myservice.xyz?q=abc
You could use the callback source option and make your own request.
http://jqueryui.com/demos/autocomplete/

Categories