How to get the $(this) to work in JQueryUI autocomplete - javascript

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

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

set data attributes with ajax and select2

I'm trying setup data attributes into select2 options but without success, at this moment i have the following JS code
_properties.$localElement.select2({
ajax: {
url: "url",
type: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
name: params.term, // search term
type: 1
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
cache: true
},
//define min input length
minimumInputLength: 3,
});
And i want setup a data-source for the selected option value.
I find the solution, looks that resultTemplate dont format the "visual" selected option , need to use templateSelection option:
templateSelection: function(container) {
$(container.element).attr("data-source", container.source);
return container.text;
}
I solved this problem.
$('select').on('select2:select', function (e) {
var data = e.params.data;
$("select option[value=" + data.id + "]").data('source', data.source);
$("select").trigger('change');
});
You can actually use the exact syntax, that you already used. The "source-attribute" just needs to be accessed via data().data.source of the specific select2-option.
So keep your processResults function like you did:
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
and if you want to retrieve the source of the selected option, you can do it like this:
var selectedSelect2OptionSource = $("#idOfTheSelect2 :selected").data().data.source;
In fact you can set any variable you want in your processResults function and then select it via data().data.variableName!

Jquery UI auto complete (with custom listing) not working

I am trying to use jquery UI autocomplete, but somehow the same won't show up despite having no javascript error.
here is my json data:
{"d":"[{\"label\":\"XYZ\",\"desc\":\"desc 1\",\"value\":\"XYZ\",\"ID\":595,\"icon\":\"UM-892983\"},{\"label\":\"ABC .\",\"desc\":\"desc 2\",\"value\":\"ABC .\",\"ID\":1681,\"icon\":\"UM-432944\"}]"}
Here is my JS Function for processing the autocomplete:
$().ready(function(){
$("#txtName").bind("keyup", function (e) {
// Ajax call returns the above json data
// On Ajax Success I call
onSucName(returnData.d);
});
});
function onSucName(result) {
var varArrAdms = $.parseJSON(result);
$("#txtName").autocomplete({
source : varArrAdms,
select : function (event, ui) {
setNameValue(ui.item.icon)
$("#txtNo").val(ui.item.icon)
$("#btnSearch").click();
},
open : function () {
$(this).addClass('loadingTxtBox');
},
close : function () {
$(this).removeClass('loadingTxtBox');
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.value + " <b> desc:" + item.desc + "</b> <i> No:" + item.icon + "</i></a>").appendTo(ul);
};
}
Where am I wrong?
Try this example
$('#txtName').autocomplete({
source: function (request, response) {
$.ajax({
url: 'url',
data: {}, //pass data here
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.icon
}
}));
}
})
},
select: function (event, ui) {
var itemval = ui.item.label;
// here you can access selected result `itemval`
return false;
},
minLength: 1
});
Why are you binding the autocomplete on keyup.... Rather you should bind it once.
Also, before rebinding it you shoud destroy the existing instance.

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