How to Add Select2 Function to a Newly Added Dynamic Select Box

Risqi Ahmad
4 min readAug 30, 2024

--

dynamic select2

Adding a dynamic select box to a web form can enhance user experience by providing a more interactive and responsive interface. One powerful tool to achieve this is the Select2 function, which makes select boxes more user-friendly by adding features like search, tagging, and infinite scrolling. In this article, we’ll guide you through the process of integrating the Select2 function into a newly added dynamic select box.

Understanding the Select2 Function

Select2 is a jQuery-based replacement for standard select boxes. It supports searching, remote data sets, and infinite scrolling of results. By integrating Select2, you can provide a better user experience in forms, especially those with a large number of options.

Steps to Add Select2 to a Dynamic Select Box

1. Include the Select2 Library

Before you can use the Select2 function, ensure that the Select2 and bootstrap library is included in your project. You can include it by adding the following links to your HTML file:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.full.min.js"></script>

2. Create a Dynamic Select Box

To dynamically create a select box, you can use JavaScript or jQuery. Below is a simple example of how to add a new select box dynamically:

HTML

<div class="row">
<div class="col-10">
<select class="form-select select2" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-2">
<button class="btn btn-primary add_btn">+</button>
</div>
</div>
<div class="mt-2 wrapper">

</div>

Javascript

$('.add_btn').on('click', function() {
$('.wrapper').append(`
<div class="row mt-2">
<div class="col-10">
<select class="form-select select2" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-2">
<button class="btn btn-primary add_btn">+</button>
</div>
</div>
`);
});

3. Apply the Select2 Function

Once the dynamic select box is created, you can apply the Select2 function to it. Here’s how:

$(document).ready(function() {
initializeSelect2();
});


let initializeSelect2 = function() {
$( '.select2' ).select2( {
theme: "bootstrap-5",
width: $( this ).data( 'width' ) ? $( this ).data( 'width' ) : $( this ).hasClass( 'w-100' ) ? '100%' : 'style',
placeholder: $( this ).data( 'placeholder' ),
});
};

This script ensures that every time a new select box is added, the Select2 function is applied, enhancing its functionality.

Handling Newly Added Elements

When dealing with dynamically added elements, it’s important to reinitialize the Select2 function every time a new select box is added. This can be done by triggering the Select2 function within the event handler that creates the select box. The following example demonstrates this:

$('.add_btn').on('click', function() {
$('.wrapper').append(`
<div class="row mt-2">
<div class="col-10">
<select class="form-select select2" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-2">
<button class="btn btn-primary add_btn">+</button>
</div>
</div>
`);
initializeSelect2();
});

Full Syntax

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<title>Select2 JS</title>

<style>
html, body {
height: 100%;
margin: 0;
}

.full-height {
height: 100%;
background: yellow;
}
</style>
</head>
<body class="bg-dark h-100">
<div class="w-25 max-w-25 mx-auto bg-light full-height">
<div class="p-2">
<div class="alert alert-primary" role="alert">
Select 2 JS
</div>
<div class="row">
<div class="col-10">
<select class="form-select select2" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-2">
<button class="btn btn-primary add_btn">+</button>
</div>
</div>
<div class="mt-2 wrapper">

</div>
</div>
</div>



<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.full.min.js"></script>

<script>
$(document).ready(function() {
initializeSelect2();
});

let initializeSelect2 = function() {
$( '.select2' ).select2( {
theme: "bootstrap-5",
width: $( this ).data( 'width' ) ? $( this ).data( 'width' ) : $( this ).hasClass( 'w-100' ) ? '100%' : 'style',
placeholder: $( this ).data( 'placeholder' ),
} );
};

$('.add_btn').on('click', function() {
$('.wrapper').append(`
<div class="row mt-2">
<div class="col-10">
<select class="form-select select2" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-2">
<button class="btn btn-primary add_btn">+</button>
</div>
</div>
`);

initializeSelect2();
});
</script>
</body>
</html>

Troubleshooting Common Issues

If you encounter any issues where the Select2 function is not applied to newly added select boxes, ensure that:

  1. Library is Loaded: Double-check that the Select2 library is correctly linked in your HTML file.
  2. Correct Event Binding: Make sure the event binding is correct and the Select2 function is triggered after the element is added.

Conclusion

Integrating the Select2 function into a newly added dynamic select box is a straightforward process that significantly improves the user experience in web forms. By following the steps outlined above, you can easily apply this functionality to your project, making your forms more interactive and user-friendly.

--

--

Risqi Ahmad

I love to share about Web Development and Data Science