Skip to content
Advertisement

Select2 multiselect select items from db with Laravel 8

I have a small problem. I have a Select2 multiselect field in my edit form. Now my goal is that my script loads all options and that the correct options are preselected.

I have already tried the whole thing, but so far it has not led to the desired result

Here is my Code

Controller snippet for the multiselect.

// Convert multiselect in right form
$product = $product['tags'];
$new = serialize($user);
$product['tags'] = $new;

edit.blade.php (snippet)

<div class="form-group">
    <label for="tag">Product Tags</label>
    <select id="tag" class="select2 select2-hidden-accessible {{ $errors->has('tags') ? 'error' : '' }}" multiple="multiple" name="tags[]" style="width: 100%;" data-select2-id="5" tabindex="-1" aria-hidden="true" value="1">
        @foreach($tags as $tag)
                <option value="{{ $tag->id }}" {{ in_array($tag->id, $prisoner->tag) ? 'selected="selected"' : '' }}>{{ $tag->label }} - {{ $tag->name }}</option>
            @endif
        @endforeach
    </select>
</div>

small js code:

$('#tag').select2({ placeholder: "Please select" }).trigger('change');

I hope someone can help me.

Advertisement

Answer

a sample of solution: with id tags

var values = $('#tags option[selected="true"]').map(function() { return $(this).val(); }).get();

// you have no need of .trigger("change") if you dont want to trigger an event
$('#tags').select2({ placeholder: "Please select" });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <body>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<select id="tags" select2 select2-hidden-accessible multiple="multiple" style="width: 300px">
    <option value="1" selected="true">Apple1</option>
    <option value="2">Bat</option>
    <option value="Cat">Cat</option>
    <option value="Dog" selected>Dog1</option>
    <option value="Elephant">Elephant</option>
    <option value="View/Exposure" >View/Exposure</option>
    <option value="View / Exposure">View / Exposure</option>
    <option value="Dummy - Data" selected>Dummy - Data</option>
    <option value="Dummy-Data">Dummy-Data</option>
    <option value="Dummy:Data">Dummy:Data</option>
    <option value="Dummy(Data)">Dummy(Data)</option>    
</select>

  </body>
</html>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement