How to change jQuery UI selector of JSON value? [closed] - jquery-ui

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have json file this type
{
"id":3,
"name": "John",
"group_id": 7,
"last_name":"Mickel"
}
I need to select last_name by jquery autocomplete.
Not "label" like is default in UI autocomplete but last_name.

Try this. It is not nice, but works.
$("#auto").autocomplete({
source: function(request, response) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
var results = $.grep( myArray, function(value) {
return matcher.test( value.last_name );
});
response(results)
}
})
.data("uiAutocomplete")._renderItem = function( ul, item ) {
console.log("test");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.last_name+"</a>" )
.appendTo( ul );
};
The source function makes it so that the filtering works. The _renderItem function makes it so that your custom name actually shows in the list.
Working fiddle: http://jsfiddle.net/eyjEg/
Note, that I belive in some of the earlier versions of jQuery it is actually .data("autocomplete").
Having said all this I also recommend reconsidering changing or transforming your JSON data model to match what the component expects. This will make it simpler and ensure, that you don't get locked into a version of jQuery as the _renderItem function is part of the internal API and subject to change.

Use a custom selector to fill in the data.
$("element").autocomplete({
source: json,
select: function(event, ui) {
$("element").val(ui.item.last_name);
});

Related

Retrieve JSON in MVC [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have an EntityFramework query in C # in an MVC, the problem is that the result of my code returns undefined, the code in C #:
public ActionResult ListarProductos()
{
sistemaEntities context = new sistemaEntities();
var lista = (from p in context.productos
select p).Where(p => p.nombre_producto.Contains(""));
return Json(new { success = true, message = lista }); // RETURN UNDEFINED
//return Json(new { success = true, message = "hola" }); // RETURN VALID OBJECT
}
The code in Ajax:
app.factory("AppService", function() {
return {
listProductos: function() {
var idata;
$.ajax({
type: 'POST',
url: "/CRUD/ListarProductos",
data: {},
dataType: 'json',
async: false,
success: function(result){idata = result;}
});
alert(idata);
return idata;
}, .. more code
The result in Ajax is "undefined" and I can not find a solution, the result in Ajax I then use it in AngularJS to display a table.
Not a duplicate, the second line of the code in c# works fine in ajax, the problem is the list in entity framework
The test line is commented out and returns a valid object
How can i fix this ?
Based on comment - return Json(new { success = true, message = new List<productos>() }); works.
It might be that productos object has circular references.
You can disable ProxyCreationEnabled, and try again.
context.Configuration.ProxyCreationEnabled = false;
Or return anonymous object with just properties that you need.
var lista = (from p in context.productos
where p.nombre_producto.Contains("")
select new { nombre_producto = p.nombre_producto }).ToList();
Please, try to change the line:
var lista = (from p in context.productos
select p).Where(p => p.nombre_producto.Contains(""));
to:
var lista = (from p in context.productos
select p).Where(p => p.nombre_producto.Contains("")).ToList();
I assume that "lista" is an list of EF proxy classes and the JSON serializer cannot serialize it.

Jquery Autocomplete unable to read Array of Objects

I am trying to use a JSON output from the server as the source for my autocomplete function. I read the Autocomplete documentation and it does say that Array of Objects is accepted as a source type. Can someone please let me know where am I going wrong with this?
jq( document ).ready(function() {
jq("body").css({overflow:'hidden'});
jq.getJSON("<?php echo Mage::getBaseUrl() . "setsession/index/getarea"; ?>",
function(data) {
jq( "#autocomplete-1" ).autocomplete({
source: data,
select: function(event, ui) {
alert(ui.item.area_id);
jq("#splash_area").val(ui.item.area_id);
return false;
}
});
}
);
});
This is what I am getting back from the server (JSON encoded):
[{"area_id":"1","area_name":"DLF Phase 1"},{"area_id":"2","area_name":"DLF Phase 2"}]
From the documentation it states an An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ].
http://api.jqueryui.com/autocomplete/#option-source
Your objects are not defined this way. So for your example something like
[{value:"1",label:"DLF Phase 1"},{value:"2",label:"DLF Phase 2"}]

AngularJs + JQueryUI waiting for response

I am trying to make some useful directives with jQueryUI widgets for my AngularJS base application.
One of them works on "select" element and am ok with directives but only thing do not understand is this one:
When select list is populated from ajax request, how to tell to apply jqueryui widget when data is populated? Suppose it is with $watch but not sure how.
Edit:
In example I am trying to implement directive for the multiselect plugin.
Please note that I am simulating server reponse but putting everything in timeout.
Here is a code on plunker
You need to be $watching changes to the items list, then calling refresh on the multiselect plugin... Here is a plunk that shows the solution
angular.module('myui', [])
.directive('qnMultiselect', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr) {
//set up the plugin.
elem.multiselect({ allowClear: false });
//get the source of the ngOptions
var parts = attr.ngOptions.split(' ');
var source = parts[parts.length - 1];
//watch the options source and refresh the plugin.
scope.$watch(source, function(value) {
elem.multiselect('refresh');
});
}
};
});

Value of Ajax generated select box not changing when called associated with jquery auto complete

The below code having a selectbox with id='theservice' and a text field with id ='servicename'.This code autocompletes the servicename text field by checking which service is active in the service selectbox.But unfortunately the source string remains the same eventhought the selectbox is changed.
$( "#servicename" ).autocomplete({
source: "index.php?key="+($('#theservice').find('option:selected').val()),
minLength: 2,
});
Thanks a Lot
Probably a delegation issue.
Autocomplete propagation example added
//build the autocomplete function, sans source
$('#servicename').autocomplete({
minLength: 2
});
var theArray = [];
$('body').on('change', 'select', function(){
$.ajax({
url: 'index.php?key='+$(this).val(),
dataType: 'json/jsonp',
success: function(data){
//i don't know what the array you return looks like, but autocomplete expets a key:value relationship
$.each(data, function(key, value){
theArray.push({label: value, value: key});
});
//a custom function to pass the array into
startAutoComplete(theArray);
}
});
});
function startAutoComplete(array){
$('#servicename').autocomplete('option', 'source', array);
}
Using the above code, we instantiate the autocomplete instance, we only identify the parameters we need excluding the source.
We then define an empty array that we can push the data returned from our ajax request into.
In our select function, we pass the value over to the server to be parsed. I don't know if you are expecting JSON/JSONP formatting, so you'll have to change that yourself.
In the success:function(data) we're getting back the request from the server, it would be best if the response was json_encode'ed. Also, when we push the values into the array, it's best to use a key -> value relationship. Autocomplete allows for a label and a value to be accessed like function(event, ui){ //do stuff with ui.item.label / ui.item.value}'
We declare an uninitialized function outside of the scope of document.ready, and pass the array into the function. Within this function, we change the source of the autocomplete.
Hope this all makes sense.
Solved the issue by using the .autocomplete( "option" , optionName , [value] ) method
$( "#servicename" ).autocomplete({
source: "index.php?key="+($('#theservice').find('option:selected').val()),
minLength: 2,
search: function( event, ui ) {
$( "#servicename" ).autocomplete( "option" ,'source' ,'index.php?key="+($('#theservice').find('option:selected').val()));}
});

use ajax call in jquery autocomplete only if result is not found in locally built array

In my web app , I am showing rates of stocks.I am using jquery autocomplete to show options while entring stocks name. But I have built local copy of javascript array. I want to show the options from this local array , If search term is not found in local array then ajax call must be made to get the list from server side.
Thanks !!!
//Local array
var local_array=["option1","option2"];
//jqueryUI call of autocomplete function
$('#search_stock').autocomplete({
source:function(){
if(search term is found in local array)
{
show suggestion from local array.
}
else
{
make ajax call to show suggestions of stock names.
}
}
});
UPDATE
Here's the actual code
$(function() {
var cache = {'option1':'option1','option2':'option2'}, lastXhr;
$( "#stock_rates" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "stock_rates.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) { response( data ); }
});
}
});
});
The example pages for jQuery UI autocomplete have an example of exactly this issue.
http://jqueryui.com/demos/autocomplete/#remote-with-cache. Click the 'View Source' link on that page to see the code for the example.
The key part is that 'source' takes arguments.
source: function(request, response){
You need to read request, either fetch the value from your cache, or do a request, and then call the response function and pass it the matched values.
Update
Your problem now is that the format that you are storing in your cache is wrong. The cache just stores data as it would be returned from your getJSON call, indexed by the search term. It is up to you do to do the prefix checking and such.
To continue the way you are trying now, you'll either need to populate the cache properly.
var cache = {
"o": ['option1', 'option2'],
"op": ['option1', 'option2'],
// ....
"option1": ['option1'],
"option2": ['option2']
};
Otherwise, you could store the data differently and put more logic in your 'source' function to do the prefix checking on a static array or something. That all really depends on the data you are caching though.
Use search event of autocomplete and check your condition in that event and based on that return true or false if you want to make a ajax call respectively.
Below is the sample code.
$('#search_stock').autocomplete({
search:function(event,ui){
if(search term is found in local array)
{
return false;
}
else
{
return true;
}
}
});

Resources