How to use chosen in jQuery
In this article, you are going to learn about how to use the chosen in jQuery.
Chosen is a jQuery plugin that is used to make large and scatter select options more user-friendly. We know that jQuery is used to make web-page more interactive and you can do many more things by writing a short amount of code. You can do the same with the chosen plugin but in a more specific section. Chosen is mainly used to make select options more catchy and user-friendly. Let’s see an example of using the chosen plugin in jQuery to make a select option interactive.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css"/>
<title>Learn Chosen jQuery</title>
</head>
<body>
<select data-placeholder="Select a Language..." class="chosen-select" multiple>
<option value=""></option>
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JavaScript</option>
<option value="python">Python</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Here, we link jQuery from the CDN first and then the chosen and the chosen CSS. You may download those files and then use them from your local machine but to make things simple we have linked the online version. Normally, to work with jQuery, we just need to link only one file but to work with the chosen plugin we need to link two files one is JavaScript and another is CSS. Finally, we take some select options and the multiple words that comes with the chosen plugin so that we can select multiple items at a single time.
JavaScript
$(document).ready(function () {
$('.chosen-select').chosen({width:"200px"});
});
Here, we simply add the functionality for the select option and you can notice that we can write CSS code into the chosen function. Let’s see the output below:
Output
Here, in the output, we can see an eye-catching select option and we can select multiple items at a single time. Moreover, when we have selected an item, that item’s color gets faded. If you notice our HTML file, we did not link our style.css file and we did not write a single line of CSS code but we can see an attractive and user-friendly output. This is possible because of using the chosen plugin. It is not possible to demonstrate every example of this plugin. For more information, you may see the documentation of chosen plugin but the process of using it is almost the same.