
JS topic
When working on web development, you often need to enhance the default HTML form elements to offer better interactivity and styling. One such enhancement is creating a custom multiple select dropdown that looks and behaves more intuitively. In this blog post, we’ll walk you through a jQuery script that transforms a standard element into a sleek, interactive multiple select dropdown.
Let’s break down the code and see how we can achieve this!
Understanding the Code:
The script is designed to replace the default multiple select dropdown with a custom dropdown UI using jQuery. It adds interactivity like toggling the dropdown, selecting and deselecting options, and displaying selected items at the top.
1. Wrapping the Element:
The script begins by targeting all elements with the multiple
attribute. The goal here is to replace the standard dropdown with a custom one.
javascript Copy code $('select[multiple]').each(function () {
For each selected element, we create a new wrapper div
that will contain our custom dropdown structure.
2. Building the Custom Dropdown UI:
For each select
element, the script creates several new elements:
- A
div
with the classselectMultiple
to wrap the entire dropdown. - A
div
for displaying selected options (initially empty). - An unordered list (
- ) to hold the available options.
- A placeholder text that is stored in the
data-placeholder
attribute of the element.
var div = $('').addClass('selectMultiple'); var active = $(''); var list = $('
- '); var placeholder = selec