Lemon Kazi Lemon Kazi - 3 months ago 25
Javascript Question

Google spreadsheet data in select box with "Chosen jQuery plugin"

I am trying to add "Chosen jQuery plugin" in my select box. Here data coming from google spreadsheet.
I tried code below under my function to append list. but this not working.

Option = "<li class="active-result">" + this.gsx$list.$t + "</li>";
$('ul.chosen-results').append(Option);


Here is my demo



function createLIST(){

// url to spreadsheet
var url = "https://spreadsheets.google.com/feeds/list/1a00YuGgCNuzYfw7C4qxvpdlbRRiDHV45gPWwQ7E6X0E/o11yyjo/public/values?alt=json";

//var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/o11yyjo/public/values?alt=json";

$.getJSON(url, function(data) {

var entry = data.feed.entry;
//function(){$('ul.chzn-results').empty();},
$(entry).each(function(){
// add each option

//Option = "<li class="active-result">" + this.gsx$list.$t + "</li>";
//$('ul.chosen-results').append(Option);
Option = "<option>" + this.gsx$list.$t + "</option>";
$('#products-list').append(Option);

});


});

}
$(document).ready(function(e){

// now add the GoogleSpread sheet list
createLIST()
//$('#products-list').chosen();

});

<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.js"></script>
<script src="http://code.jquery.com/jquery.min.js"></script>
<datalist id='products'>

</datalist>

<select id='products-list'>
</select>




Answer

Initialize chosen plugin only after options are added from the JSON response.

function createLIST() {

  var url = "https://spreadsheets.google.com/feeds/list/1a00YuGgCNuzYfw7C4qxvpdlbRRiDHV45gPWwQ7E6X0E/o11yyjo/public/values?alt=json";

  $.getJSON(url, function(data) {
    var entry = data.feed.entry;
    $(entry).each(function() {
      Option = "<option>" + this.gsx$list.$t + "</option>";
      $('#products-list').append(Option);
    });

    // initialize chosen after options are added 
    $('#products-list').chosen();

  });
}
$(document).ready(function(e) {
  createLIST();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.js"></script>
<datalist id='products'>

</datalist>

<select id='products-list'>
</select>

Comments