Select2 provides a solution where a regular select option turned into an awesome search option where I can search and find my desired option, with a single line of code. So let’s get dive into it.
When you are creating a UI that has select boxes where the user selects an option from it. But that is very disgusting to find out desired option from a long listed ordinary select options.
First, include jquery and select2 file in the HTML document where you want to use it.
Add this CSS link in the head
tag of your HTML document:
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
And select2 and jquery script in the footer area:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
This is a simple select option:
<select id="the-select-option">
<option value="orange">Orange</option>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
</select>
Now make this awesome by calling the function and done. Like this:
<script>
$('#the-select-option').select2();
</script>
Select2 gives us a plethora of options where we can do whatever we want to. Here is the link of full documentation.
Let’s see an example using ajax
:
We will use the array data source here.
Let’s assume you are giving the user to choose their favourite fruit. For that you have a dataset coming from a URL (say this URL: http://example.com/api/fruits
). And the result looks like this:
[
{
id: 1,
text: "Orange"
},
{
id: 1,
text: "Apple"
},
{
id: 1,
text: "Banana"
}
];
Now first we need to get the data using ajax
, after getting all data in an array
, we will assign it to select2. Like this:
$.ajax({
url: 'http://example.com/api/fruits',
success: function(result) {
$('.select-option').select2({
data: result
});
}
});
After parsing the result id is assigned in the value part in an option and text is as text what we can see in an option. <option value="[the id]">[the text]</option>
That’s it. You are done.
There are other options out there that will replace ordinary select boxes with some cool features like (Chosen, Seletize etc). I personally prefer select2 because it has a large community, the interface is familiar with bootstrap and they update regularly which makes them a bit ahead in the race.