Select2 jQuery plugin is easy to add on the <select > element. Need to call the select2() method on the selector to initialize.
If you adding select2 on a class or select element and when you add an element dynamically then select2 is not initialized on that element.
In this tutorial, I show how you can initialize select2 on dynamically created HTML <select > element using jQuery.
I am loading select2 data using jQuery AJAX in the example.
Contents
1. Table structure
I am using users
table in the example –
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. Configuration
Create a config.php
for a database connection.
Completed Code
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. Download
- Download the Select2 library from GitHub and also download the jQuery library.
- Extract the downloaded files in the project directory.
- Also, copy the jQuery library.
4. HTML
Create a <select class="select2_el" >
element to initialize select2 on page load and create <div id="elements" >
container to store <select >
element on button click using jQuery AJAX.
Completed Code
<select class="select2_el" style='width: 200px;'> <option value='0'>- Search user -</option> </select> <div id='elements'> </div> <input type="button" id="btn_add" value="Add">
5. AJAX
Create ajaxfile.php
file for handling AJAX requests.
Handle two requests –
- If
$request == 1
then return data for select2.
Check if searchTerm
is POST or not. If not POST then fetch all records from users
table otherwise use POST value to search on name
field in users
table to fetch records.
Loop on the fetched records and initialize $data
Array with id
and text
keys. Pass $row['id']
in id
key and $row['name']
in text
key.
Return $data
Array in JSON format.
- If
$request == 2
then return<select class="select2_el" >
element.
Completed Code
<?php include 'config.php'; $request = 1; if(isset($_POST['request'])){ $request = $_POST['request']; } // Select2 data if($request == 1){ if(!isset($_POST['searchTerm'])){ $fetchData = mysqli_query($con,"select * from users order by name limit 5"); }else{ $search = $_POST['searchTerm']; $fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5"); } $data = array(); while ($row = mysqli_fetch_array($fetchData)) { $data[] = array("id"=>$row['id'], "text"=>$row['name']); } echo json_encode($data); exit; } // Add element if($request == 2){ $html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>"; echo $html; exit; }
6. jQuery
Create initailizeSelect2()
function to initialize select2()
on class="select2_el"
. Use AJAX to load select2 data.
Call initailizeSelect2()
function on document ready state.
Define click event on #btn_add
. Send AJAX POST request to 'ajaxfile.php'
file to add <select >
element on #elements
by appending the response
in #elements
.
Again call the initailizeSelect2()
function to reinitialize the select2 on class="select2_el"
.
Completed Code
$(document).ready(function(){ // Initialize select2 initailizeSelect2(); // Add <select > element $('#btn_add').click(function(){ $.ajax({ url: 'ajaxfile.php', type: 'post', data: {request: 2}, success: function(response){ // Append element $('#elements').append(response); // Initialize select2 initailizeSelect2(); } }); }); }); // Initialize select2 function initailizeSelect2(){ $(".select2_el").select2({ ajax: { url: "ajaxfile.php", type: "post", dataType: 'json', delay: 250, data: function (params) { return { searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); }
7. Demo
8. Conclusion
You need to reinitialize select2 on the dynamic element.
In the example, I created <select > element using jQuery AJAX and initializing it in class. You can follow the same way to initialize select2 if you are not creating an element using jQuery AJAX.
You can initialize it on element id instead of class if you are getting the id.
If you found this tutorial helpful then don't forget to share.