jquery ui autocomplete without filter - jquery-ui

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.

Related

Select2 AJAX doesn't update when changed programatically

I have a Select2 that fetches its data remotely, but I would also like to set its value programatically. When trying to change it programatically, it updates the value of the select, and Select2 notices the change, but it doesn't update its label.
https://jsfiddle.net/Glutnix/ut6xLnuq/
$('#set-email-manually').click(function(e) {
e.preventDefault();
// THIS DOESN'T WORK PROPERLY!?
$('#user-email-address') // Select2 select box
.empty()
.append('<option selected value="test#test.com">test#test.com</option>');
$('#user-email-address').trigger('change');
});
I've tried a lot of different things, but I can't get it going. I suspect it might be a bug, so have filed an issue on the project.
reading the docs I think maybe you are setting the options in the wrong way, you may use
data: {}
instead of
data, {}
and set the options included inside {} separated by "," like this:
{
option1: value1,
option2: value2
}
so I have changed this part of your code:
$('#user-email-address').select2('data', {
id: 'test#test.com',
label: 'test#test.com'
});
to:
$('#user-email-address').select2({'data': {
id: 'test#test.com',
label: 'test#test.com'
}
});
and the label is updating now.
updated fiddle
hope it helps.
Edit:
I correct myself, it seems like you can pass the data the way you were doing data,{}
the problem is with the data template..
reading the docs again it seems that the data template should be {id, text} while your ajax result is {id, email}, the set manual section does not work since it tries to return the email from an object of {id, text} with no email. so you either need to change your format selection function to return the text as well instead of email only or remap the ajax result.
I prefer remapping the ajax results and go the standard way since this will make your placeholder work as well which is not working at the moment because the placeholder template is {id,text} also it seems.
so I have changed this part of your code:
processResults: function(data, params) {
var payload = {
results: $.map(data, function(item) {
return { id: item.email, text: item.email };
})
};
return payload;
}
and removed these since they are not needed anymore:
templateResult: function(result) {
return result.email;
},
templateSelection: function(selection) {
return selection.email;
}
updated fiddle: updated fiddle
For me, without AJAX worked like this:
var select = $('.user-email-address');
var option = $('<option></option>').
attr('selected', true).
text(event.target.value).
val(event.target.id);
/* insert the option (which is already 'selected'!) into the select */
option.appendTo(select);
/* Let select2 do whatever it likes with this */
select.trigger('change');
Kevin-Brown on GitHub replied and said:
The issue is that your templating methods are not falling back to text if email is not specified. The data objects being passed in should have the text of the <option> tag in the text property.
It turns out the result parameter to these two methods have more data in them than just the AJAX response!
templateResult: function(result) {
console.log('templateResult', result);
return result.email || result.text;
},
templateSelection: function(selection) {
console.log('templateSelection', selection);
return selection.email || selection.id;
},
Here's the fully functional updated fiddle.

jQuery autocomplete origin

I'm adding autocomplete on several inputs at the same time, thus writing a single handling function as the source. I'd like to have the id attribute of the origin (the input that triggered the action) available in my handling function. But it seems there's no direct reference to it within autocomplete...
$('#inputForm #supplier, #inputForm #label').autocomplete({
source: function(request, response) {
$.post("autocomplete.php", {id: ???, term: request.term}, success);
}
});
Any clue?
Got it! Thanks to Richard ;)
$(this.element).attr('id')
Complete code, in case anyone would be interested:
$('input').autocomplete({
source: function(request, response) {
$.post("autocomplete.php", {origin: $(this.element).attr('id'), term: request.term}, success);
}
});
you could use
$(this).attr('id')
I suggest you also use a class for all your autocomplete like for example
.autocomplete
and add data- for your extra data like
data-id, data-url
you can get the value of data-xxx attributes by using
$(this).data('id') and $(this).data('url')
enter code here
$(".autocomplete")
.each(function () {
$(this).autocomplete({
source : function(request, response) {
$.post($(this).data('url'), {origin: $(this.).data('id'), term: request.term}, success);
}
});
});

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

Resources