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);
}
});
}
Related
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');
I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.
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);
}
});
});
}
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');
}
}
});
});
Only started today but I'm having massive problems trying to understand JSON/AJAX etc, I've gotten my code this far but am stumped on how to return the data being pulled by the AJAX request to the jQuery Auto complete function.
var autocomplete = new function() {
this.init = function() {
$('#insurance_destination').autocomplete({
source: lookup
});
}
function lookup() {
$.ajax({
url: "scripts/php/autocomplete.php",
data: {
query: this.term
},
dataType: "json",
cache: false,
success: function(data) {
for (key in data) {
return {
label: key,
value: data[key][0]
}
}
}
});
}
}
And example of the JSON string being returned by a PHP script
{
"Uganda": ["UGA", "UK4", "Worldwide excluding USA, Canada and the Carribbean"]
}
Normally, you don't have to do ajax query yourself:
$('#insurance_destination').autocomplete('url_here', {options_here});
That's assuming we're talking about standard jquery autocomplete plugin. Do I understand you correctly?
edit
Check api
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
There are also some examples.
This is the code I've ended up with, it works in Chrome and Firefox but not in IE 6/7...
var autocomplete = new function (){
this.init = function() {
$('#insurance_destination').autocomplete({
source: function(request, response) {
debugger;
$.ajax({
url: "scripts/php/autocomplete.php",
dataType: "json",
data: {query:this.term},
success: function(data) {
response($.map(data.countries, function(item) {
return {
label: '<strong>'+item.name+'</strong>'+' '+item.description,
value: item.name,
code : item.region
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$('#insurance_iso_code_hidden').val(ui.item.code);
},
open: function() {
},
close: function() {
}
});
}
}