Autocomplete with json data - javascript

I have two problems with this code:
json example:
{"json_list": [{"label": "Porto Rico", "value": 33}, {"label": "Portugal", "value": 32}]}
$("#user_country_name").autocomplete({
source : function(request, response) {
$.getJSON("/users/autocomplete/" + request.term, function(data) {
response(data.json_list);
});
},
});
First when I choose a country the selected value in the input box should be the label and not the value. Because the user should see the country and not the id.
Second, how can I populate the hidden field $("#user_country_id") for the id of the chosen country?

Use the select method
select: function( event, ui ) {
event.preventDefault();
$("#user_country_name").val(ui.item.label);
}

What you need to do, is to parse the json response. if you have any problems to get access use console.log().
$( "#w-arrival-search" ).autocomplete({
select: function (e, ui) {
$("#w-arrival-search").val(ui.item.label);
return false;
},
minLength: 3,
source: function (request, response) {
$.ajax({
url: 'http://localhost:8080/mvn/autocomplete',
data: request,
success: function (data) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject, function (item) {
var results = item.iata_code + " - " + item.city_name;
return {
label: results
};
}));
}
});
}
});

Related

ajax auto-completion bind data to textbox

Am getting data from ajax call, How to bind data for text box auto-completion with name and id as fields.
How to bind the data in front end and get selected name's id in back end java.
$(document).ready(function() {
$(function() {
$("#customerName").autocomplete({
source : function(request, response) {
$.ajax({
url : "/customer/getByNames",
type : "GET",
data : {
name : $("#customerName").val()
},
dataType : "json",
success : function(data) {
response(data);
}
});
}
});
});
});
<input type="text" id="customerName" name="customerName"
th:field="*{customer.name}" />
JSON returned data from ajax call (Data at sucess)
[
{"id": 1,"name": "Customer_01"},
{"id": 2,"name": "Customer_02"},
{"id": 3,"name": "Customer_03"},
{"id": 4,"name": "Customer_04"}
]
Need to bind name field of JSON to textbox as auto-completion
Can any one help me?
You can pass the data from your AJAX call to a method to initialize the auto complete plugin.
The method can have a name of selectors to initialize or if your selectors are in the data then you can map the data to an array of selectors you want to bind auto complete for.
$(document).ready(function()
$.ajax({
url : "/customer/getByNames",
type : "GET",
data : {
name : $("#customerName").val()
},
dataType : "json",
success : function(data) {
setAutoComplete(data);
}
});
});
function setAutoComplete(data)
{
var selectors = ["#someId", "someotherId"];
//if your selector are in the data then use data.map to get your selectors.
selectors.forEach(function(selector)
{
$(selector).autocomplete({
source: data
});
}
}
If your data has a special format you can use a custom render function to initialize the auto complete plugin.
For example, this allow you to group auto complete data with a category and field into groups using this JSON set as formModel:
{
"Contact":{
"FirstName":"Contact.FirstName",
"MiddleInitial":"Contact.MiddleInitial",
"LastName":"Contact.LastName",
"Address1":"Contact.Address1",
"Address2":"Contact.Address2",
"City":"Contact.City",
"State":"Contact.State",
"PostalCode":"Contact.PostalCode",
"WorkPhone":"Contact.WorkPhone",
"HomePhone":"Contact.HomePhone",
"Email":"Contact.Email"
},
"UDFs":{
"ModifiedBy":"Contact.UDFs.ModifiedBy",
"ModifiedDate":"Contact.UDFs.ModifiedDate",
"SessionId":"Contact.UDFs.SessionId",
"FormData":"Contact.UDFs.FormData"
}
}
I use this code:
function getFormModel() {
var availableTags = [];
for (var category in formModel) {
var fields = formModel[category];
for (var field in fields) {
availableTags.push({
category: category,
label: field,
value: fields[field] });
}
}
return availableTags;
}
function setAutoComplete(el) {
$(el).autocomplete({
source: getFormModel(),
create: function () {
//access to jQuery Autocomplete widget differs depending
//on some jQuery UI versions - you can also try .data('autocomplete')
$(this).data('uiAutocomplete')._renderMenu = customRenderMenu;
}
});
}
var customRenderMenu = function (ul, items) {
var self = this;
var categoryArr = [];
function contain(item, array) {
var contains = false;
$.each(array, function (index, value) {
if (item == value) {
contains = true;
return false;
}
});
return contains;
}
$.each(items, function (index, item) {
if (!contain(item.category, categoryArr)) {
categoryArr.push(item.category);
}
console.log(categoryArr);
});
$.each(categoryArr, function (index, category) {
ul.append("<li class='ui-autocomplete-group'>" + category + "</li>");
$.each(items, function (index, item) {
if (item.category == category) {
self._renderItemData(ul, item);
}
});
});
};
Final working code :
$(document).ready(function() {
$(function() {
$("#customerName").autocomplete({
source : function(request, response) {
$.ajax({
url : "/customer/getByNames",
type : "GET",
data : {
name : $("#customerName").val()
},
dataType : "json",
success : function(data) {
$("#customerName").autocomplete({
source : data
});
},
appendTo: "#customerNameResult"
});
}
});
});
});

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 $(this) to work in JQueryUI autocomplete

Here is a fiddle example
I have trouble getting the $(this) to work in the source function with jQueryUI autocomplete.
The console shows that the search input isn't able to get its data attribute 'name' before sending out an Ajax request. Is there any way to pass the variable "name" to data?
$('.input').autocomplete({
source: function (request, response) {
var name = $(this).data('name');
console.log(name);
$.ajax({
url: url,
dataType: "json",
data: {
'q': request.term,
'field': name
},
success: function (data) {
response($.map(data.query.results.json.json, function (item) {
return {
label: item.name,
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(this).val(ui.item.label);
$(this).val(ui.item.label);
},
open: function () {
$(this).autocomplete("widget").width(400)
}
});
You should use this.element to access corresponding input element. this points to the autocomplete instance itself:
var name = $(this.element).data('name');

How to populate extra fields with jQuery autocomplete

I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}

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