How to Do

How to make a searchable drop-down list in HTML

Pinterest LinkedIn Tumblr

Scrolling a big list of countries, states or cities is annoying sometimes when you are filling a form asking your country to select. Today I come up with a solution to make a searchable drop-down list, very happy to share it with you :).

Today in this tutorial I will tell you how to make a searchable drop-down list in HTML, CSS. You can create a static dropdown but I am creating it to dynamic. Check this demo.

Problem

As you know the problem, that’s why you are here for the solution. LOL…, So the problem is this, suppose you have created a form in your website or web application, you have a long dropdown list to select it as you might have seen on a variety of websites. You need to scroll it until you did not find the item you are looking for.

coding-birds-online-how-to-make-a-searchable-drop-down-list-problem

Solution

The solution is select2. Select2 is a jQuery based replacement for select boxes. It supports searching remote data sets and infinite scrolling of results.

When you will integrate this, you will get a search box at the top of the select dropdown list. Now you can search the item you are looking for in a long list. You can check the installation guide also on the official website.

<link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>

Import these CDN links to the head of the HTML page and paste this shortcode to the footer to make your dropdown list searchable.

// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
    $('.your-select-dropdown-class').select2();
});

Don’t worry I will show you how to code step by step. I am creating this select 2 dropdown list dynamic by fetching the countries from the database. Let’s check the folder structure.

Addidtionally, I will show country flags in the dropdown, to make it more beautifull and eye catchy to the users.

coding-birds-online-how-to-make-a-searchable-drop-down-list-folder-structure

Step by step to code

  • Create an index.php file to show the select dropdown list.
  • config.php is the connection file to the database.
  • flags folder contains all the flags of the countries. I will provide it.

Now create these files.

index.php complete code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>
    <title>How to make searchable dropdown with country flag - Coding Birds Online</title>
    <style>.required{color: #FF0000;}
           .flag{background-color: #ff884b;padding: 10px;border-radius: 20px;color: white}
    </style>
</head>
<body>
<div class="container">
    <?php
    include "config.php";
    $query = "SELECT * FROM bird_searchable_dropdown";
    $countries = $connection->query($query);
    ?>
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center><img width="50" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"></center>
                    <h5 class="card-title text-center">Searchable dropdown with country <span class="flag">FLAG</span></h5>
                    <form>
                        <div class="form-label-group">
                            <label for="inputEmail">Country <span class="required">*</span></label>
                            <select  name="select2" id="select2" class="form-control">
                                <option value="">Select</option>
                                <?php
                                if ($countries->num_rows>0){
                                    while ($country = $countries->fetch_object()){ ?>
                                        <option value="<?php echo $country->code;?>"><?php echo $country->countryname;?></option>
                                   <?php  }
                                }
                                ?>
                            </select>
                        </div> <br/>
                        <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-md btn-primary btn-block text-uppercase" >Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("#select2").select2({
        templateResult: formatState
    });
    function formatState (state) {
        if (!state.id) {
            return state.text;
        }
        var baseUrl = "flags";
        var $state = $(
            '<span><img src="' + baseUrl + '/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
        );
        return $state;
    }
</script>
</body>
</html>

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Run the Code to get the searchable drop-down list

When you run the code you will get this output as I told above in the solution.

coding-birds-online-how-to-make-a-searchable-drop-down-list-final-output

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here

Check this https://minhaskamal.github.io/DownGit/ link to download a single folder(flags folder) from a repository on GitHub.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

I am a professional Web / Software developer, B.Tech CSE, who has been working in PHP & CodeIgniter and WordPress for more than 2+ years and know it inside and out, including the creation of Web Apps, WordPress websites from scratch and their customization.

1 Comment

  1. Dwight Batun Reply

    Some really excellent content on this internet site, appreciate it for contribution.

Write A Comment