Jquery Autocomplete unable to read Array of Objects - jquery-ui

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"}]

Related

Using select2 with json data that doesn't have a field called "text" while avoiding copying the items and loosing standard behaviors

I'm using select2 and I want to set a custom field for the text property of the rendered items without
replacing standard behavior (marking and such)
pushin all my array into a new one with the text field on it
ps: i just want to a render many select2 items that doesn't have a text field
Basically if you see this jsbin you will see something like this
$("#e10_3").select2({
data:{ results: data, text: function(item) { return item.tag; } },
formatSelection: format,
formatResult: format
});
But if I delete the custom formatSelection and formatResult parameters of select2 I loose my hability to use a different field for text.
I suggest this approach
$("#e10_3").select2({
data:{
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.tag,
id: item.id
...
}
})
};
}
},
formatSelection: format,
formatResult: format
});
As previous answer this solution DOES create a new array, but it seems to be a better approach considering readability. Before passing data you should modify it. You can see this in official docs
var data = $.map(yourArrayData, function (obj) {
obj.text = obj.text || obj.name; // desired field
return obj;
});
The only other option is to prepare data with text property matched to desired property from the very beginning.
UPDATE (added an example)
$('your-select2-el').select2
data: $.map(yourArrayData, (obj) ->
obj.text = obj.your_custom_field_name # obj.title or obj.name etc.
obj
)
See docs in the link I provided before and this one

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

how to attach a callback to Bootstrap Typeahead plugin

Using the custom bootstrap plugin for typeahead functionality
https://gist.github.com/1891669
How to attach a callback for 'select' event?
The following code doesn't work.
var selectedFn = $('.typeahead dropdown-menu').on('select', function( ev ){
console.log(ev);
});
Can someone explain how this works?
A new way of doing this is:
$('.input').typeahead({
// snip
}).on('typeahead:selected', function() {
// on selected
});
$('#myselector').typeahead({
itemSelected:function(data,value,text){
console.log(data)
alert('value is'+value);
alert('text is'+text);
},
//your other stuffs
});
You have to just pass itemSelected in the callback function and it will give you the selected item.
Hope this will work for you.
You can just listen to your inputs change event like this:
$('input.typeahead').on('change', function () { ... })
Specify the arguments in the function that handles the event in order to get the value selected as suggested in the documentation at https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#custom-events
.on('typeahead:select', function(ev,value) {
//value = the selected object
//e.g.: {State: "South Dakota", Capital: "Pierre"}
})
It gives exactly the same result with typeahead:select instead of typeahead:selected. I'd rather go with the one which is documented.
$('.typeaheadGroupSelect').typeahead({
// snip
}).on('typeahead:selected', function(data, value, text) {
// on selected
console.log(data);
console.log(value.idPublic); // here you can access all json object by using value.key
console.log(value.name);
});
I used above code snippet to access data from the selection and assign certain hidden values to another input.
Prior I added an object to the data source typeahead is using to query data, see below:
var jsonData = [
{"id":"1","idPublic":"978343HFJ","name":"Volkswagen Group Sales International"},
{"id":"2","idPublic":"8343JJR98","name":"BMW Group Sales APAC"},
{"id":"3","idPublic":"935723JFF","name":"Jaguar Group Sales Asia"},
{"id":"4","idPublic":"3243JFUFF","name":"Mercedes Benz Group Sales Europe"}
];

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

jquery ui autocomplete without filter

I need to show user all autocomplete choices, no matter what text he already wrote in the field? Maybe i need some other plugin?
$('#addressSearch').autocomplete("search", "");
That doesn't work.
There are two scenarios:
You're using a local data source. This is easy to accomplish in that case:
var src = ['JavaScript', 'C++', 'C#', 'Java', 'COBOL'];
$("#auto").autocomplete({
source: function (request, response) {
response(src);
}
});
You're using a remote data source.
$("#auto").autocomplete({
source: function (request, response) {
// Make AJAX call, but don't filter the results on the server.
$.get("/foo", function (results) {
response(results);
});
}
});
Either way you need to pass a function to the source argument and avoid filtering the results.
Here's an example with a local data source: http://jsfiddle.net/andrewwhitaker/e9t5Y/
You can set the minLength option to 0, then it should work.

Resources