HTML Autocomplete Dropdown List

HTML Autocomplete Dropdown List
Project: Bootstrap Autocomplete Dropdown
Author: btn.ninja
Edit Online: View on CodePen
License: MIT

This HTML code snippet helps you to create an autocomplete dropdown list. It defines a form with text input that is enhanced with an autocomplete feature using jQuery. When the user types in the input field, a dropdown menu appears below it, which lists four options. The list of options is defined using Bootstrap’s dropdown-item class. If the user types in a value that does not match any of the options, the message “No matching results” appears.

The autocomplete feature also works with copy/paste. The code includes some additional notes cautioning that this autocomplete feature is only intended for short lists and is not a replacement for typeahead.js, which is designed for more complex server interactions.

How to Create HTML Autocomplete Dropdown List

First of all, load the Bootstrap CSS by adding the following CDN link into the head tag of your HTML document.

<link rel='stylesheet' href='https://btn.ninja/css/bootstrap.css'>

Create the HTML structure for the autocomplete dropdown as follows:

<form style="width:500px; margin:50px auto;">

  <label>Type Alpha</label>  <div class="dropdown">
    <input type="text" class="jAuto form-control" 
           placeholder="Type the word Alpha" autocomplete="off">
    <div class="dropdown-menu">
        <i class="hasNoResults">No matching results</i>
        <div class="list-autocomplete">
            <button type="button" class="dropdown-item">01 - Alpha  Barbuda</button>
            <button type="button" class="dropdown-item">02 - Charlie Alpha</button>
            <button type="button" class="dropdown-item">03 - Bravo Alpha</button>
            <button type="button" class="dropdown-item">04 - Delta</button>
        </div>
        <button type="button" class="btn-extra">Custom button</button>
    </div>
  </div>  

  <small style="margin-top:30px">This will search the text of a list placed inside Bootstrap dropdown: also works with copy/paste. <em>Note</em>: Only use this on short lists; it is not a replacement for typeahead.js, which is built for more complex server interactions. Tested in ie9+ and in production environment with 1m users.</small>
  <small style="margin-top:10px"><em>See also:</em> <a class="link" href="https://codepen.io/btn-ninja/pen/PodpoBd" target="_blank">Bootstrap5 version</a> (untested in production)</a>
</form>

Now, style the autocomplete dropdown using the following CSS styles:

mark { background-color:pink; }

form{
background-color: black;
padding: 40px 60px;
color: white;
border-radius: 10px;
}
.list-autocomplete {
  padding:0; }
.list-autocomplete em {
  font-style:normal;
  background-color:#e1f2f9;
}

.hasNoResults { 
  color:#aaa; }
.hasNoResults,
.btn-extra { 
  display:block; 
  padding:10px; }

.hasNoResults { 
  color:#aaa; }

.btn-extra { 
  width:100%; 
  border-top:.5px solid #d2d2d2; }

Load the jQuery by adding the following CDN link before closing the body tag:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>

Finally, add the following JavaScript function to activate the autocomplete functionality:

//code = 2k minified

function createAuto (i, elem) {

    var input = $(elem);
    var dropdown = input.closest('.dropdown');
    var listContainer = dropdown.find('.list-autocomplete');
    var listItems = listContainer.find('.dropdown-item');
    var hasNoResults = dropdown.find('.hasNoResults');

    listItems.hide();
    listItems.each(function() {
         $(this).data('value', $(this).text() );  
         //!important, keep this copy of the text outside of keyup/input function
    });
    
    input.on("input", function(e){
        
        if((e.keyCode ? e.keyCode : e.which) == 13)  {
            $(this).closest('.dropdown').removeClass('open').removeClass('in');
            return; //if enter key, close dropdown and stop
        }
        if((e.keyCode ? e.keyCode : e.which) == 9) {
            return; //if tab key, stop
        }

      
        var query = input.val().toLowerCase();

        if( query.length > 1) {

            dropdown.addClass('open').addClass('in');

            listItems.each(function() {
             
              var text = $(this).data('value');             
              if ( text.toLowerCase().indexOf(query) > -1 ) {
 
                var textStart = text.toLowerCase().indexOf( query );
                var textEnd = textStart + query.length;
                var htmlR = text.substring(0,textStart) + '<em>' + text.substring(textStart,textEnd) + '</em>' + text.substring(textEnd+length);
                $(this).html( htmlR );               
                $(this).show();
 
              } else { 
              
                $(this).hide(); 
              
              }
            });
          
            var count = listItems.filter(':visible').length;
            ( count > 0 ) ? hasNoResults.hide() : hasNoResults.show();

        } else {
            listItems.hide();
            dropdown.removeClass('open').removeClass('in');
            hasNoResults.show();
        }
    });

  	listItems.on('click', function(e) {
        var txt = $(this).text().replace(/^\s+|\s+$/g, "");  //remove leading and trailing whitespace
        input.val( txt );
        dropdown.removeClass('open').removeClass('in');
		});

}

$('.jAuto').each( createAuto );


$(document).on('focus', '.jAuto', function() {
     $(this).select();  // in case input text already exists
});

That’s all! hopefully, you have successfully integrated this HTML code for autocomplete dropdown list. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *