My Script
$("#NameSearch").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/home/universalsearch/" + document.getElementById("filterUniversalSearchList").value + "/" + $("#NameSearch").val(),
type: "POST",
dataType: "json",
data: {
searchFilter: document.getElementById("filterUniversalSearchList").value,
term: request.term,
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeName, id: item.EmployeeID}
}))
}
});
},
focus: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<div>" + item.label + "<br>" + item.id + "</div>")
.appendTo(ul);
};
});
Controller:
public JsonResult UniversalSearch(string searchFilter, string searchText)
{
var Employees = _home.GetEmployeeDetails(searchFilter, searchText);
return Json(new { data = Employees }, JsonRequestBehavior.AllowGet);
}
Problem I'm facing is in autocomplete dropdown I'm getting as undefined.
From controller it return as object array
I think I made mistake in binding data improperly.
dropdown result shows as undefined.
Is this problem due to jqueru-ui versions ?
Related
I am developing textbox with autocomplete using jQuery UI Autocomplete.
After that, I can create textbox with autocomplete, but one issuce has occured now.
In my textbox, I want to prevent selecting specific item from autocomplete list.
If I select specific item, Autocomplete list display again or not to close.
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
});
});
});
If someone know answer, please teach me.
Based on the example from here: How to disable element in jQuery autocomplete list
I think this code will work for you:
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
//Add the .ui-state-disabled class and don't wrap in <a> if value is empty
var id = item.id
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else{
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
};
});
If you can provide a working version of your code (the items can also be from a predefined list, not based on ajax call) it will be much easier to help.
Using Jquery autocomplete UI widget, I have the following code that gets a list of suburbs/postcodes via external php:
<script>
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
}
});
});
</script>
The autocomplete itself works well, I get the list of matches , however the 'select' part does not work, ie, I need to set another input text value to the value selected, but even in the above code, the Alert dialog does not get called - the various syntax I've seen has kind of confused me, so I'm not sure what I've done wrong here.
The selectfunction should be outside of the object that is sent to the ajax method.
Try this:
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
}
});
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
});
I return a class object but only XRCFOR textbox is populate correctly. Select events seems no work.
Through a WebServe I return object items. Select event on a row however is only populated the XRCFOR textbox. Here is the Html/razor/Jquery code. Thanks.
<td>
#Html.EditorFor(model => model.XRUDBF, Functions.GetAdditionalViewData(ViewData["PageStatus"].ToString(), ViewData["PageReadonly"].ToString(), "form-control"))
#Html.EditorFor(model => model.XRCFOR, Functions.GetAdditionalViewData(ViewData["PageStatus"].ToString(), ViewData["PageReadonly"].ToString(), "form-control"))
#Html.EditorFor(model => model.XRCFORDescription, new {htmlAttributes= new { #class = "form-control", #readonly = "readonly" }})
<script type="text/javascript">
$("#XRCFOR").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Zoom/GetFOR/",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.B5CFOR + " - " + item.B5RGS1, value: item.B5CFOR
};
}))
}
})
},
select: function (event, ui) {
$("#XRUDBF").val(ui.item.B5CUDB);
$("#XRCFOR").val(ui.item.B5CFOR);
$("#XRCFORDescription").val(ui.item.B5RGS1);
},
//messages: {
// noResults: '',
// results: function () { }
//},
minLength: 1
});
</script>
</td>
I've found this solution
success: function (data) {
response($.map(data, function (item) {
return {
label: item.B5CFOR + " - " + item.B5RGS1, value: item.B5CFOR, extravalue: item
};
}))
}
and then
select: function (event, ui) {
$("#XRUDBF").val(ui.item.extravalue.B5CUDB);
$("#XRCFORDescription").val(ui.item.extravalue.B5RGS1);
},
works fine!
I am working on jQuery autocomplete which as two items in a <ul>.
I am getting json item from $.getJSON function and the json object looks like :
[{
"merchant_name": "Myntra",
"merchant_details": "Flat Rs.225 Cashback"
}, {
"merchant_name": "Adlabs imagica",
"merchant_details": "Rs 170 per sale"
}, {
"merchant_name": "godaam",
"merchant_details": "Rs 140 per sale"
}, {
"merchant_name": "Homeshop18",
"merchant_details": "Upto 8% Cashback"
}]
My function looks as follows:
$('#search_bar').keyup(function(e) {
var searched = $('#search_bar').val()
$.getJSON('<?php echo base_url();?>get_data', 'title=' + searched, function(result) {
var elements = [];
$.each(result, function(i, val) {
elements.push({
'merchant_name': val.merchant_name,
'merchant_details': val.merchant_details
})
}) $('#search_bar').autocomplete({
delay: 0,
source: elements,
select: function(event, ui) {
$("input#search_bar").val(ui.item.merchant_name + " / " + ui.item.merchant_details);
$("#get").click();
}.data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a><strong>" + item.merchant_name + "</strong> / " + item.merchant_details + "</a>").appendTo(ul);
};
})
})
});
I am not able to proceed forward.
Please help me to solve this one.
I wrote this for one of my projects and it works perfectly. I'm not sure why you are detecting keyup when autocomplete does that for you... But this snippet should give you all the functionality you need.
$("#edit_profile .location").autocomplete({
source: function(request, response) {
$.ajax({
url: BASE_URL + "lib/ajax.php",
type: "GET",
data: "autocomplete_location=1&term=" + request.term,
cache: false,
success: function(resp) {
try {
json = $.parseJSON(resp);
} catch (error) {
json = null;
}
//
if (json && json.status == "OK") {
//
response($.map(json.predictions, function(item) {
return {
label: item.description,
value: item.description
}
}));
//
}
}
});
},
minLength: 1,
change: function (event, ui) {
if (!ui.item){
$(this).val("");
}
}
});
I've been ripping my hair out for a few hours now and can't seem to find out why i've got an error.
When i call the following code :
$(document).ready(function () {
$("#searchBox").autocomplete({
select: function (event, ui) {
$("#searchBox").attr("readonly", true);
//this is where if i call alert(ui.long) I get undefiend
$("#CoorLong").val(ui.long);
$("CoorLat").val(ui.lat);
print_r(ui);
},
source: function (request, response) {
$.ajax({
url: "http://dev.virtualearth.net/REST/v1/Locations",
dataType: "jsonp",
data: {
key: "bingKey",
q: request.term
},
jsonp: "jsonp",
success: function (data) {
var result = data.resourceSets[0];
if (result) {
if (result.estimatedTotal > 0) {
response($.map(result.resources, function (item) {
return {
data: item,
label: item.name + '[' + item.point.coordinates[0] + ' ' + item.point.coordinates[1] + ']' + ' (' + item.address.countryRegion + ')',
value: item.name,
long: item.point.coordinates[0],
lat: item.point.coordinates[1]
}
}));
}
}
}
});
},
minLength: 1
});
});
As I said in the selec: function(event, ui) when i call ui.item or ui.value or ui.long I always get undefined
I implemented a print_r() to check the content and I do get this :
[item] =>object[data] =>object[__type] =>Location:http://schemas.microsoft.com/search/local/ws/rest/v1[bbox] =>object[0] =>48.83231728242932[1] =>2.2598159619433122[2] =>48.840042717570675[3] =>2.275464038056688[name] =>Quai d'Issy-les-Moulineaux, 75015 Paris[point] =>object[type] =>Point[coordinates] =>object[0] =>48.83618[1] =>2.26764[address] =>object[addressLine] =>Quai d'Issy-les-Moulineaux[adminDistrict] =>IdF[adminDistrict2] =>Paris[countryRegion] =>France[formattedAddress] =>Quai d'Issy-les-Moulineaux, 75015 Paris[locality] =>Paris[postalCode] =>75015[confidence] =>Medium[entityType] =>RoadBlock[label] =>Quai d'Issy-les-Moulineaux, 75015 Paris[48.83618 2.26764] (France)[value] =>Quai d'Issy-les-Moulineaux, 75015 Paris[long] =>48.83618[lat] =>2.26764
So i don't understand why it's undefined.
Thank you :)
From the documentation:
ui.item refers to the selected item.
So I think you want ui.item.long instead of ui.long.