Chosen: Fetch From Remote Data Source

Created on 27 Jul 2011  ·  47Comments  ·  Source: harvesthq/chosen

Is there some sample code which shows how it works with jQuery UI Autocomplete feature? If not can we have this as a feature request?

Feature Request

Most helpful comment

@juanghurtado: if i have a multi-select box that contains 300K items i cant really write it out into html entirely. Chosen provides the perfect interface for searching and selecting. there are many other libraries that provide this functionality, ie [1], [2] and many more. Out of all these Chosen works the best, but it doesnt support very large collections - which is what the remote datasource support would add. Also, if Chosen supported this it would mean having to skin and keep up to date one plugin instead of two.

[1] http://loopj.com/jquery-tokeninput/
[2] http://wharsojo.wordpress.com/2008/02/18/jquery-facebook-autocomplete/

All 47 comments

This is a bit better then jquery auto complete isn't it? I would like to see remote data sources eventually (the ability to provide a callback for the search results)

I third this request. This would be very handy to have the ability to specify an remote source just like the jQuery UI autocomplete feature.

Or maybe even better: Include chosen in jQuery UI. :)

+1

more specifically my +1 is for the idea of using a remote data source with free-text entry (e.g. using ajax calls to aid in tagging)

Sorry, I wasn't clear enough, but "remote data source" integration is what I originally meant, thanks for pointing that out. Of course, this plugin is far better than the jQuery Auto Complete feature. As daFish commented, I would love to see this as part of jQuery UI itself.

+1 for remote datasource support

I don't get it. Chosen is about better usability and beauty on SELECT elements, not about autocomplete or fetching remote data. If you want remote data, collect it and put it into de DOM before the Chosen call…

@juanghurtado: if i have a multi-select box that contains 300K items i cant really write it out into html entirely. Chosen provides the perfect interface for searching and selecting. there are many other libraries that provide this functionality, ie [1], [2] and many more. Out of all these Chosen works the best, but it doesnt support very large collections - which is what the remote datasource support would add. Also, if Chosen supported this it would mean having to skin and keep up to date one plugin instead of two.

[1] http://loopj.com/jquery-tokeninput/
[2] http://wharsojo.wordpress.com/2008/02/18/jquery-facebook-autocomplete/

Well, if you have 300k items on your SELECTitem, (IMHO) you hare doing something wrong… There are many options to handle that interface in a better way.

Chosen could do may things… Like swish army knives, it could do lot of things (remote datasources, image association to items, custom filtering, AJAX queries…) and stop being the perfect tool for just one (better interface for traditional SELECT elements).

El 10/08/2011, a las 22:56, ivaynberg escribió:

@juanghurtado: if i have a multi-select box that contains 300K items i cant really write it out into html entirely. Chosen provides the perfect interface for searching and selecting. there are many other libraries that provide this functionality, ie [1], [2] and many more. Out of all these Chosen works the best, but it doesnt support very large collections - which is what the remote datasource support would add. Also, if Chosen supported this it would mean having to skin and keep up to date one plugin instead of two.

[1] http://loopj.com/jquery-tokeninput/
[2] http://wharsojo.wordpress.com/2008/02/18/jquery-facebook-autocomplete/

Reply to this email directly or view it on GitHub:
https://github.com/harvesthq/chosen/issues/79#issuecomment-1776643

cant really argue with that...

I want to get remote data when searching from chosen, like jquery autocomplete plugin, pls help me

+1 to have support for remote data.

any u look ur UI is nice, but some issues are have, like not support remote data.

I think this is doable but not as easy as one might think. Since this is github and open source lets look at some code.

@juanghurtado I also think we can do this without bloating the existing functionality, both jquery and prototype give us everything we need for remote data sources.

results_search() seems to be triggered during keypresses - that's where I would override chosen's default behavior. I need to dig a little deeper but it looks like if we can mimic winnow_results() and add a way to show loading behavior (eg. winnow_loading_results()) this could work fine.

Another function to look at is winnow_results_clear();

The hard part is figuring out how to smoothly integrate this into Chosen. Should it be in the options? Should it be just a subclass? And is this something the core devs would let into the master project?

Actually - we should close this issue, a lot of work is being done on #162 which seems to being everything we'd want.

Just thought I would add that in this day age this functionality is a must and I really hope it gets implemented soon. In every other way chosen is perfect. :)

What happened that fetching from remote data source issue?

Time for @pfiller to join the conversation I guess.

+1 I would love to see this

I am loading the remote values at once when the page is served so if I cant update or fetch new data, if I could at least add new options to the select then I could maintain client side until the page is refreshed. So +1 to remote fetching and/or +1 ability to add new options. Hope this makes sense...

+1 for jaloka request

yo tengo una tabla con 17500 registros y cuando cargo la pagina se vuelve lenta y por ultimo se bloque... creo que si se pudiera implementar la forma de ir a buscar coincidecias en la tabla seria lo mejor.

Someone has implemented it: https://github.com/meltingice/ajax-chosen

I'm not a jQuery guru and actually I know nothing about it. So please forgive my clueless way to explain things. I really can't find the right words to describe my issue. I just followed that simple instruction: added a class, put the script and called the function. Everything worked great, except the page which didn't have select input on it. And I'm not sure that data goes with a help of Ajax. All I can suppose is that forms are generated from MySQL database's table. Select input's options go from there. At least it looked like when I edited the page. So when I load the page I see only 'chzn-select' class in my select input which means script doesn't work at all. Reading related issues I understood that it's because of remote data source, but I don't understand how to fix it. Actually I don't really get what you guys are talking about here. I tried Ajax-chosen provided above with no success and I tried other 'hacks' mentioned here. Can someone explain with simple words is it possible to do something in my case or not?

I'm using jQuery 1.4.2, tried both on Mac OS and Windows. You can check it here: http://94.125.8.168/eng/ (click Search or Timetable tab in the center block called Flight information). Selects Destination, Flight number and Airport are supposed to have Chosen.

@ffiona You need to wrap your Chosen call in a jQuery ready function.

$(document).ready(function() {
  $(".chzn-select").chosen();
});

Please try to keep future questions on-topic for a thread. If you have a question, you are welcome to open a new issue.

@pfiller is this a feature you guys are/or will work on? i've tried all the other ajax-chosen hacks but none of them really work. i really need this because i'm working on a stock exchange app that user types in stock symbols which as you know can have tens of thousands of them.

@all it seems like my option for getting the ajax auto complete from chosen will be a long shot and i may have to look for alternatives. anyone can recommend any other alternatives to chosen w/ this feature?

I also created one recently.. https://github.com/ksykulev/chosen-ajax-addition

@ksykulev do you happen to have a live demo of this somewhere?

@jaequery
Just quickly hacked together an example http://sykulev.com/ajaxchosen/index.html

I added the code under /example in my repository.

@ksykulev : your version does a really great job with single selects, thanks ! Btw it does not work with multiselect. I may have a look at this if I have some spare time.

The version of @meltingice does really weird things on multiselect too, I think it's because it doesn't use Chosen functions at all (so all the things that are naturally resolved in the original lib are not in the ajax version, for instance input repositionning and resizing after the results are sent back to the client).

@jbbarth: Yes you are correct, I haven't tested it with multiselects so I can only imagine it doesn't work very well. In terms of the completeness of my library I can definitely add support for these. I will get on it. Thanks!

i ended up rolling my own version with look and feel based on Chosen.

https://github.com/ivaynberg/select2

it supports ajax/jsonp remote datasets and infinite scrolling (lazy loading of paged remote datasets). no support for multiselect yet though.

@ivaynberg I'm all eyes on this.

Once you hit feature parody with Chosen (specifically tag-like multiselect support), you should definitely bump this thread.

I love the look and feel of Chosen, but it really leaves things to be desired in implementation.

Very, very nice work!

@ivaynberg I noticed you still have code from chosen that specifically calculates drop-down and search input widths.

You may want to check this out : https://github.com/harvesthq/chosen/pull/407

I recently updated my ajax chosen version to support multiple selects. http://sykulev.com/ajaxchosen/index.html

@justindujardin Select2 master now has feature parity. i will take a look at the sizing stuff in 407, but we should take further discussions to Select2's project.

I freaking love Select2 and i recommend EVERYONE switching over to it. Heh.

@ProLoser – thanks for that... exactly what I was looking for. Looks like a much better option.

Select2 FTW!

Select2 is the way to go!

Any updates after all these years?

Why missing such imp feature?

hmm... that stinks. I decided to implement Chosen because of the text highlighting but didn't realize AJAX was going to be so difficult to add. I guess I should have gone with select2 if everyone is jumping ship from this to go to that as a way to meet requirements. :(

It's a great feature. Many forks proposes this feature but the implementation is often chaotic. :+1:

I have come up with an easy monkey patch solution:

AbstractChosen.prototype.winnow_results = (function(winnow_results) {
  return function() {
    if (this.options.source) {
      return this.options.source.call(this.form_field, this.search_field.val(), (function(_this) {
        return function(results) {
          var id, option, select;
          if (results) {
            select = document.createElement('select');
            select.appendChild(document.createElement('option'));
            for (id in results) {
              if (results.hasOwnProperty(id)) {
                option = document.createElement('option');
                option.value = id;
                option.textContent = results[id];
                select.appendChild(option);
              }
            }
            _this.results_data = SelectParser.select_to_array(select);
          }
          return winnow_results.call(_this);
        };
      })(this));
    } else {
      return winnow_results.call(this);
    }
  };
})(AbstractChosen.prototype.winnow_results);

You can provide a 'source' function option for chosen which will be called on results render. It will have string input value and callback function arguments. The callback function renders suggestions. If the results should not have changed, then you should call it immediately without arguments, else you can request for results and send them to the callback when you've got them. The results object has this format: { value: "label", value2: "label2" }. Here is an example:

var select = $("#select"),
    value;
select.chosen({
    source: function (val, callback) {
        if (value != val) {
            value = val;
            $.get('/suggestions', { value: value }, callback);
        } else
            callback();
    }
});

What @faucct suggests seems to work. A minor note though is that if you are using jquery version you won't be able to access AbstractChosen, outside of the chosen scope, so you probably want to add those files to the inside chosen's scope or you will need to modify chosen js file and move AbstractChosen and SelectParser to global scope. Another problem is that, it updates the open list (div's that chosen creates) but it does not update the actual "select field" therefore an option you selected if it does not exist in the select might throw an error. A thing to note as well is that, the string you wrote is used to filter the results you return as well. Also it works every time you type something so you have control manually to not make calls.

I have found another extension is this: https://github.com/meltingice/ajax-chosen

It works pretty well but the current version is broken, you have make some minor modifications. You have to replace "chzn" with "chosen" as chosen library has changed it's internal css names. Last change you need to do is to trigger "chosen:updated" instead of "listz:updated". In the readme it asks you to fix a bug in the css but it's already fixed in newer versions, so you don't need to do that. You can also set some useful options and if user keeps writing, system cancels the pending calls as well.

This was my journey :), hope it helps.

I have solved this problem by creating a plugin that handles remote data source for chosen, hope you all can enjoy it

chosen-remote-source (https://github.com/westonganger/chosen-remote-source)

The entire code is fairly simple at with less than 200 lines of code
https://github.com/westonganger/chosen-remote-source/blob/master/src/chosen-remote-source.js

The only part of Chosen that was required to patch was the following:

// MONKEY PATCH CHOSEN TO NOT CLEAR THE SELECTED RESULTS UPON SEARCHING WITH
chosen_prototype.show_search_field_default = function() {
  if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
    this.search_field.val(this.default_text);
    return this.search_field.addClass("default");
  } else {
    if(this.default_text === this.search_field.val()){
      this.search_field.val(""); // ORIGINAL LINE, SURROUNDING IF STATEMENT IS CUSTOM
    }

    return this.search_field.removeClass("default");
  }
};
// END CHOSEN PATCH
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbrooksuk picture jbrooksuk  ·  6Comments

raggzy picture raggzy  ·  5Comments

gandarez picture gandarez  ·  5Comments

mcclurem picture mcclurem  ·  4Comments

SFPink picture SFPink  ·  4Comments