简体   繁体   中英

grouped options select with jquery

I have json object for which i am trying to write a grouped_options using jquery. My json object looks like this

data = {"01 CONSULT":[["1b Rules","40"]],"02 DEVELOPMENT":[],"03 QUALITY":[],"05 MARKETING":[["5e Research","66"]],"06 MISCELLANEOUS":[["6a Training","69"],["6b Meetings","70"]}

My dropdown should look like this :

 **01 CONSULT**
   1b Rules
 **02 DEVELOPMENT**
 **03 QUALITY**
 **05 MARKETING**
   5e Research
 **06 MISCELLANEOUS**
   6a Training
   6b Meetings

My code currently looks like this. I am not able to get the parent values in the dropdown as I am struggling to write the jquery with grouped_options.

  function change(data){
    $("#task_id").empty();
      for(var y in data){
        $("#task_id").append(
        $("<option></option>").attr("value", y).text(data[y]).appendTo("optgroup");
  );

} }

Any help would be appreciated..Thanks!

I am not sure if this is your complete code in the function, but you are not creating an optgroup

 var data = { "01 CONSULT": [ ["1b Rules", "40"] ], "02 DEVELOPMENT": [], "03 QUALITY": [], "05 MARKETING": [ ["5e Research", "66"] ], "06 MISCELLANEOUS": [ ["6a Training", "69"], ["6b Meetings", "70"] ] }; change(); function change() { var $select = $('#task_id'); for (d in data) { var parent = d; var children = data[d]; console.log(d); var $optgroup = $('<optgroup/>', { label: d, }).appendTo($select); for (c in children) { var child = data[d][c]; $('<option/>', { value: child, html: child }).appendTo($optgroup); } } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="task_id"> </select> 

Your current code doesn't append any optgroup elements. Maybe you can do something like this:

 data = {"01 CONSULT":[["1b Rules","40"]],"02 DEVELOPMENT":[],"03 QUALITY":[],"05 MARKETING":[["5e Research","66"]],"06 MISCELLANEOUS":[["6a Training","69"],["6b Meetings","70"]]} function change(data){ var slct = $("#task_id") slct.empty() Object.keys(data).forEach(function(og) { // for each data key var optgroup = $("<optgroup></optgroup>", {label: og}) // create optgroup element data[og].forEach(function(opt) { // for each option $("<option></option>", { // create option element value: opt[1], text: opt[0] }).appendTo(optgroup) // append option to group }) optgroup.appendTo(slct) // append group to select }) } change(data) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="task_id"></select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM