Sooraj Chandran Sooraj Chandran - 5 months ago 42
CSS Question

Get classes on original option to select2 dropdown

I have the following code for a select2 dropdown. My aim is to get all the attributes from the

<option level="2" data-type="ci_type" value="44">Sales Service</option>
,

on the select2 dropdown list which looks like this now

<li class="select2-results-dept-0 select2-result select2-result-selectable"><div class="select2-result-label"><span class="select2-match"></span> Sales Service</div></li>


Is this possible?
During my research i found
formatResultCssClass
option , but not sure how to use this.



$(document).ready(function() {

$("#my_select2_dropdown").select2({

})
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css" rel="stylesheet" />

<label>Value:</label>
<select id="my_select2_dropdown" style="">
<option style="padding-left:0em" level="0" data-type="type" value="1">value1</option>
<option style="padding-left:1em" level="1" data-type="type" value="2">value2</option>
<option style="padding-left:2em" level="2" data-type="type" value="4">value3</option>
<option style="padding-left:2em" level="2" data-type="type" value="5">value4</option>
<option style="padding-left:1em" level="1" data-type="type" value="7">value5
</select>




Answer

Found a solution at last. Here is the code. Do not know if this is the best option or not , but it certainly works.

jQuery("#myselect2dropdown option").each(function(i,e){
        jQuery("#myselect2dropdown").data('select2').dropdown.find("li:eq("+i+")").attr("data-type",jQuery(e).attr("data-type"));
      }); 
Comments