Q:

How can I assign select2 plugin to select element which has plugin options as json object at data attribute?

I use many select2 plugin and I want to assign options and options values of plugin from related element's data attribute as like below;
HTML
<select data-plug="select2" data-plug-op='{"placeholder":"text1","containerCssClass":"maincss"}'>
    <option></option>
</select>

<select data-plug="select2" data-plug-op='{"placeholder":"text2","containerCssClass":"maincss2","dropdownCssClass":"dropdowncss"}'>
    <option></option>
</select>

JS
var slc = $('[data-plug="select2"]');

assignSelect(slc);

function assignSelect(selectElement) {

    selectElement.each(function(){

        var $this  = $(this),
            plugOp = $.parseJSON( $this.attr('data-plug-op') );

        /*-- --*/
        $.each(plugOp,function(k,v){

           $this.select2({
             k:v
           });

        });
        /*-- --*/

    });

}

I get options from related element's data attribute and parse it as JSON but I can't assign to plugin. How can I do this?

A:

Probably i've found a solution to your problem
In this Fiddle the attribute data-plug-op of the two options is used to build the plugin select2 object.
Since in this case i don't knew maincss and maincss2 i used width and placeholder for differentiating the two options
the code seems to work the first options has a placeholder = "text1" and a width of 200
the second option has a placeholder="text2" and width=400
All jQuery code you need is
<script type="text/javascript">
$(document).ready(function() {
     $.each($('[data-plug="select2"]'),function(index){
         obj={}
         var $this  = $(this),
            plugOp = $.parseJSON( $this.attr('data-plug-op') );

        for(prop in plugOp) {
            obj[prop]=plugOp[prop]
        }
        $('[data-plug="select2"]:eq('+index+')').select2( $.extend({}, obj))
    })

});
</script>

A more sintetic way to obtain the same result coul be this Fiddle
 where i use a bit of css to differentiate two options group
<script type="text/javascript">
$(document).ready(function() {
     $.each($('[data-plug="select2"]'),function(index){
         var $this  = $(this)
         var plugOp = $.parseJSON( $this.attr('data-plug-op') );
        $('[data-plug="select2"]:eq('+index+')').select2(plugOp)
    })
});
</script>

The last solution could be
(But for its conciseness I prefer the second solution)
<script type="text/javascript">
$(document).ready(function() {
    var slc = $('[data-plug="select2"]');
    assignSelect(slc);
    function assignSelect(selectElement) {
        selectElement.each(function(){
            var $this  = $(this),
            plugOp = $.parseJSON($this.attr('data-plug-op'));
            $this.select2(plugOp);
        });
    }   
});
</script>

