Home » Jquery » Select 2 jQuery doesn't work in laravel 6

Select 2 jQuery doesn't work in laravel 6

Posted by: admin February 22, 2020 Leave a comment

Questions:

So I am trying to create a form where the user can add a book to the database.
I wanted to use the select bars from Select2, which allow the user to search for the select elements.
I followed a tutorial on how to make this work, but somehow it doesn’t seem to work for me.
Any ideas on what I did wrong?

The relevant code:

@extends('layout')


@section('title')
<title>Add new book</title>
@section('stylesheets')
<link href="css/select2.min.css" rel="stylesheet" />
<script src="js/select2.min.js"></script>
@endsection
@section('content')
<style>
    .uper {
        margin-top: 40px;
    }
</style>
<div class="card uper">
    <div class="card-header">
        Neues Buch hinzufügen
    </div>
    <div class="card-body">
        <form method="post" action="{{ route('books.store') }}">
            <div class="form-group">
                @csrf

                ...

            <div class="form-group">
                <label for="authors">Author(en):</label>
                <select name="authors[]" multiple class="form-control select2-multi <!-- @error('authors') is-invalid @enderror -->">
                    @foreach ($authors as $author)
                    <option value="{{ $author->id }}">{{ $author->name }}</option>
                    @endforeach
                </select>
                @error('authors')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

...

 </form>
    </div>
</div>
@endsection
<script type="text/javascript">
$('.select2-multi').select2();
</script>
How to&Answer:

Seeing the code as is, your script tag is outside of your sections, thus not getting read inside the file, move it inside any section really, but in this cas the stylesheets would be more appropriate.

@section('stylesheets')
<link href="css/select2.min.css" rel="stylesheet" />
<script src="js/select2.min.js"></script>
<script type="text/javascript">
    $('.select2-multi').select2();
</script>
@endsection

While we’re at it, your title section doesn’t have an endsection.