0
votes

I am working on jquery select2 dropdown. I have to display the multiple selected option in select area. For this purpose i loop through each of select2. If condition is met i will assign 'selected' attribute property to option so that it may appears in the select area. But somehow the select2 fails to display the selected ''.

HTML CODE:

<div class="form-group col-md-12">
    <label for="inputsskill">Skill<span class="required-field">*</span></label>
         <fieldset>
              <select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
               @if(!$skills->isEmpty())
                   @foreach($skills as $skill)
                      <option value="{{$skill->id}}">{{$skill->name}}</option>
                   @endforeach
               @endif
             </select>
         </fieldset>
 </div>

JQUERY CODE:

// parse skills
var parseData = JSON.parse(skill);
// parseData is an array which contain 1,2,3 values like ['1','2','3']
$("#skill_name > option").each(function() {
// if select2 and array values matches assign selected attribute to that option
    if( $.inArray($(this).val(), parseData) !== -1 ) {
        $(this).attr('selected', 'selected');
    }
});

Select2 Jquery:

$( "#skill_name" ).select2({
});

I dont know where i am going wrong, i would appreciate if someone guide me in this. Thanks,

1

1 Answers

0
votes

you can achieve this functionality with PHP easily. E.g : fetch skills from the database which you want to preselect and create an array of skills. Then match this in your loop.Like

 <div class="form-group col-md-12">
        <label for="inputsskill">Skill<span class="required-field">*</span></label>
             <fieldset>
                  <select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
                   @if(!$skills->isEmpty())
                       @foreach($skills as $skill)
                          <option value="{{$skill->id}}" <?php
                            if(in_array($skill->name, $selectedskillsArray)){
                                   echo $selected = 'selected';
                                }
                            ?> >{{$skill->name}}</option>
                       @endforeach
                   @endif
                 </select>
             </fieldset>
     </div>

Try this one.

Jquery solution

$( "#skill_name" ).select2({
});
$('#skill_name').val(["1","2","3"]).trigger('change');