Sunday, March 9, 2014

Select2 gotcha's and Other Useful Parameters


  • If you followed the steps in previous post, you could have a working select2 where select options are filled with JSON response coming from a remote request. But you would find it unable to select an option from the drop-down. This is because Select2 requires an id property to be set for items returned in the 'results' parameter. This can be done in 2 ways:

  1. Add 'id' object in the JSON response, in which case the response will be an Array of JSON objects like below:
  2. [{"id":"1","text":"Abhijeet"},{"id":"2","text":"Abhishek"},{"id":"3","text":"Anurag"},{"id":"4","text":"Anuj"},{"id":"5","text":"Gaurav"},{"id":"6","text":"Subodh"},{"id":"7","text":"Phani"}]
    
  3. Use the 'id' call-back function. So in our original example from previous post, we can add the below option in the select2 constructor (in custom_myselect.js). Remember this is not part of 'ajax' options, it is a separate option by itself.
    id: function(data) { return data.text; }
Going with option 1 of adding 'id' in the JSON response, i observed that after selection, if we submit the form the value(s) given in 'id' are sent to get or post action. As a user, we might think that the value selected - i.e 'text' should be forwarded, but gotcha. Option 2 solve this issue and therefore i prefer using it.


  • When 'multiple' option is set to true - i.e select2 is configured to have multiple options selected - by default comma (,) is used as separator. If in case your data also includes commas, you can use the 'separator' option to define your own separator.
  • 'initSelection'  function call-back  allows the user to initialize the selection based on the value of the element select2 is attached to. Make note that this doesn't work if the element (to which select2 is attached) is not already populated with a value. In that case use the 'data' method to set the selection.
  • minimumInputLength - Number of characters that are necessary before making a request.



1 comment:

  1. Hi,

    for me it is not working... I also had to change the below part in order to get the json results in the dropdown, but still can't select also after adding id function... can you please help me? what could be the issue?

    data: function (parms,term) {
    return {
    tag_word: parms.term,
    };

    ReplyDelete