Select2 : Works only in one select option but not in two or more select options

640 Views Asked by At

I am using Select2 for my select options. It works when I add the js-example-basic-single class to a select option but it seems like whenever I add the same class to other select boxes in the same page, it won't work on them. Am I doing something wrong?

<ul class="list-group" id="here">
  <li class="list-group-item row" ng-repeat="element in mylist">
    <div class="col-sm-5">
      <select id='element' class="js-example-basic-single form-select" name="element-{{$index}}" ng-model="finalView.details" ng-change='setStatus()' required="true">
        <option class="text-uppercase" ng-repeat="item in Views" ng-value="item">{{item.viewname}}</option>
      </select>
    </div>
    <button class="col-sm-1 btn btn-outline-danger" ng-click="removeChoice($index)" ng-if="mylist.length >1"><i data-feather="x-circle"></i></button>
    <button class="col-sm-1 btn btn-outline-primary" ng-click="addNewChoice()" ng-if="mylist.length==1"><i data-feather="plus-circle"></i></button>
  </li>
</ul>

<script>
 $(document).ready(function() {
       $('.js-example-basic-single').select2();
 });
</script>
2

There are 2 best solutions below

0
inquisitive On

I don't know how it works but I rewrote the same code again with very minor changes. Anybody's welcome to explain this if they know why. This is the code that works:

<ul class="list-group" id="here">
  <li class="list-group-item row" ng-repeat="element in mylist">
    <div class="col-sm-5">
      <select class="js-example-basic-single form-select" name="element-{{$index}}" ng-model="finalView.details" ng-change='setStatus()' required="true">
        <option class="text-uppercase" ng-repeat="item in Views" ng-value="item" selected='selected'>{{item.viewname}}</option>
      </select>
    </div>
    <button class="col-sm-1 btn btn-outline-danger" ng-click="removeChoice($index)" ng-if="mylist.length >1"><i data-feather="x-circle"></i></button>
    <button class="col-sm-1 btn btn-outline-primary" ng-click="addNewChoice()" ng-if="mylist.length==1"><i data-feather="plus-circle"></i></button>
  </li>
</ul>
0
M G On

It seems that having 2 select options with the same ID on your page may cause "select 2" to only affect the last one, which could explain why only one of your select options was displayed in the desired format while the other did not.