Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 and initSelection callback

On page load, I'm trying to use initSelection to select ID 60 (specified value of the input field). I can't seem to get it to work properly.

The PHP scripts work great and return the correct values, but how do I get the JS to do the callback correctly?

JavaScript:

$(document).ready(function() {     $('#editAlbumArtistId').select2({             placeholder: 'Search names',             ajax: {                 url: "/jQueryScripts/jQuerySelectListArtists.php",                 dataType: 'json',                 quietMillis: 100,                 data: function (term, page) {                     return {                         term: term, //search term                         page_limit: 10 // page size                     };                 },                 results: function (data, page) {                     return {results: data.results};                 }              },             initSelection: function(element, callback) {              var id = $(element).val();             if(id !== "") {                 $.ajax("/jQueryScripts/jQuerySelectListArtists.php", {                     data: {id: id},                     dataType: "json"                 }).done(function(data) {                     callback(data);                 });             }         }     }); }); 

HTML:

<p>     <input type='hidden' value="60" data-init-text='Search names' name='editAlbumArtistId' id='editAlbumArtistId' style="width:180px;"/> </p> 

Every time I refresh the page, I see that the PHP script gets executed and that it returns the proper ID and text. However, the field isn't updated and I've seriously tried everything I can think of.

I'm using Select2 3.4.3.

Any help would be greatly appreciated.

like image 309
Mad Marvin Avatar asked Sep 19 '13 20:09

Mad Marvin


People also ask

What is initSelection in Select2?

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter.

What is the use of Select2 in jQuery?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


1 Answers

Finally solved it! I figured select2 didn't want an array since it's a single value, so I selected the first element of the data.results array.

callback(data.results[0]); 

And if you have set multiple:true, just accept the entire results array;

callback(data.results); 
like image 54
Mad Marvin Avatar answered Sep 24 '22 14:09

Mad Marvin