Open In App

How to create dynamic autocomplete search using Bootstrap Typeahead ?

In this article, we will learn to implement dynamic autocomplete search using Bootstrap Typeahead. Bootstrap Typeahead is a plugin that helps to add a beautiful autocomplete option in the search bar. 

In this approach, we will be taking static data for autocomplete, but we can also use dynamic JSON data as well, to show search options. The methods used in the Typeahead plugin are as follows.



Example: The following example demonstrates the dynamic autocomplete search using Bootstrap Typehead.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
    <script src=
    </script>
      
    <script src=
    </script>
      
    <link href=
        rel="stylesheet" />
  
    <style>
        .typeahead {
            width: 50%;
            top: 60px !important;
            left: 50px !important;
        }
    </style>
</head>
  
<body style="text-align: center">
    <div>
        <b><p>Suggest the states of India</p></b>
  
        <input type="text" class="typeahead" 
            data-provide="typeahead" 
            placeholder="Enter name of states of India " />
    </div>
  
    <script>
      
        // Initializes  input( name of states)
        // with a typeahead
        var $input = $(".typeahead");
        $input.typeahead({
            source: [
                "Andhra Pradesh",
                "Arunachal Pradesh",
                "Assam",
                "Bihar",
                "Chhattisgarh",
                "Goa",
                "Gujarat",
                "Haryana",
                "Himachal Pradesh",
                "Jharkhand",
                "Karnataka",
                "Kerala",
                "Madhya Pradesh",
                "Maharashtra",
                "Manipur",
                "Meghalaya",
                "Mizoram",
                "Nagaland",
                "Odisha",
                "Punjab",
                "Rajasthan",
                "Sikkim",
                "Tamil Nadu",
                "Telangana",
                "Tripura",
                "Uttar Pradesh",
                "Uttarakhand",
                "West Bengal",
            ],
            autoSelect: true,
        });
  
        $input.change(function () {
            var current = $input.typeahead("getActive");
            matches = [];
  
            if (current) {
  
                // Some item from your input matches
                // with entered data
                if (current.name == $input.val()) {
                    matches.push(current.name);
                }
            }
        });
    </script>
</body>
  
</html>

Output:



dynamix automatic typeahead


Article Tags :