I will keep adding more js package that I use or you might use when you're using jQuery in the stack, this time is Select2
. Select2
gives you additional input on the <select>
element to filter the options. Now let's find out how to add it to your laravel app with Laravel-Mix.
Prerequisites to code along
Have your own laravel app and you ever use sass/scss and javascript with laravel (using laravel-mix). Not to mention, you already have jQuery installed in your app.
Installing Select2
Open your terminal, go to your laravel app, and here is the command to install:
npm install select2 --save-dev
Applying Select2 JS
In your entrypoint or bootstrapped js file, you may have a similar code like this:
window._ = require('lodash');
try {
window.$ = window.jQuery = require('jquery');
} catch (error) {
console.log(error);
}
now we just add the select2 below the jquery requirement and apply the select2 globally to any <select>
element in your web (You may want to change it to your preference):
window._ = require('lodash');
try {
window.$ = window.jQuery = require('jquery');
require('select2');
$('select').select2();
} catch (error) {
console.log(error);
}
Applying Select2 CSS
At this point, your select2 won't work unless you apply the style as well. In your sass/scss entrypoint file, add this line:
...
@import "~select2/dist/css/select2.css";
...
Build!
npm run development
or
npm run production
Test it!
Let's put this simple select
html element from w3schools in your web:
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
And see it whether it applies or not by yourself, let me know if it doesn't 👻.
version used:
node v14.16.0
npm 6.14.11
laravel-mix 6.0
Top comments (2)
Thanks bro, you helped me a lot!
glad this old tips helped you