Oscar LT
Oscar LT

Reputation: 797

Bootstrap select2 not working with js function

I have the following code:

In html

<select multiple id="e1" style="width:200px"></select>

In js I have a function to fill the options.

$('#e1').select2();
   for (var i in this.notSelected) {
     var options = '<option data-idx="'+ i +'">' + this.notSelected[i][field] + '</option>';
     $('#e1').append(options);
   }

If I click in the editText I can see the options but I can't select anything.

Any examples or help about this?

Thanks.

Upvotes: 2

Views: 486

Answers (1)

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

You should use for loop like this. It is not good approach to access DOM so many time. So do this after for loop.

  var options = '';
  for (var i=0;i<this.notSelected.length;i++) {
      var temp = this.notSelected[i];
      var options += '<option value="'+ temp +'">' + temp[field] +'</option>';
  }
  $('#e1').append(options);

Below is the running code.

$(document).ready(function(){
    $('#e1').select2();
    var ad = ['Op1', 'Op2', 'Op3'];
    var op = '';
    for (var i=0; i<ad.length;i++){
        op += '<option data-idx="'+i+'">'+ad[i]+'</option>';
    }
    $('#e1').append(op);
});
<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
        <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1-rc.1/css/select2.min.css" rel="stylesheet" />
        <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1-rc.1/js/select2.min.js"></script>
        <meta charset="utf-8">
        <title>JS Bin</title>
    </head>
    <body>
        <select multiple id='e1' style="width: 400px;">

        </select>
    </body>
</html>

Upvotes: 1

Related Questions