javascriptjquerylaraveljquery-pluginsjquery-select2

Select 2 only working on the first element of an array


I have an array and am using select 2 inside that array. Select 2 is working on the first element but in the other elements select 2 is not working.

My html:

@foreach($quizzes as $quiz)

<select class="js-example-basic-multiple grades" multiple id="grades" name="grades[]">
<option value="1">Form 1 History</option>
<option value="2">Form 2 History</option>    
</select>
@endforeach

My script:

 <script>
$("#grades").select2();
$("#checkbox").click(function(){
  if($("#checkbox").is(':checked') ){
    $("#grades > option").prop("selected","selected");// Select All Options
    $("#grades").trigger("change");// Trigger change to select 2
  }
  else{
    $("#grades > option").removeAttr("selected");
    $("#grades").trigger("change");// Trigger change to select 2
  }
});

$("#button").click(function(){
  alert($("#grades").val());
});
$("#grades").select2({
  placeholder: "To be done by...",
  allowClear: true
});

 </script>

I can't seem to find out what is wrong.


Solution

  • Try initializing select2 by class name instead of ID. Element IDs should be unique throughout the DOM.

    $(".grades").select2({
      placeholder: "To be done by...",
      allowClear: true
    });
    

    And remove the first $("#grades").select2();