Improve your skills

September 14, 2016

Add Simple Auto Complete Search to Input Box like Google using JQuery UI


In this tutorial, we learn how to implement auto-complete search textbox like google using jQuery UI. We can easily display a list of suggestions from the beginning of the word typed in a text box. Auto-complete prevents the user from having to enter an entire word or a set of words.

Here we have implemented a basic autocomplete with a local array as its data source. The source option is mandatory to which we are specifying a local array of strings. Once the user starting to enter country name, the auto suggested countries would be listed under the textbox. These auto suggested countries would be fetched from the list of the countries defined in our array.

First, we declare a input text box in <body> element as show in below-

HTML:
<body>
    <form>
        <input id="txtSearch" type="text" placeholder="Search Country" /><br/>
        <span id="lblMsg" style="color:green;"></span>
    </form>
</body>

After that, attach the jQuery library and jQuery UI link on your <head> part of page and write the below javascript code in head part shown as below-

JS:
<head>
<title>Add Simple Autocomplete Search to input box using jQuery UI</title>

<!-- Load jQuery, jQuery UI and jQuery ui styles from jQuery website -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script type="text/javascript">

/* list of array of countries as its local data source*/
var data = ["Afghanistan", "Australia", "Bangladesh", "Canada", "China", "France", "Germany", "India", "Indonesia", "Iran", "Italy", "Japan", "Nepal", "New Zealand", "Pakistan", "Russia", "Saudi Arabia", "Sri Lanka", "United Arab Emirates", "United Kingdom", "Zimbabwe"];

$(document).ready( function () {
/* binding the text box with the jQuery Auto complete function. */
$("#txtSearch").autocomplete({
/*source refers to the list of countries that are available in the auto complete list. */
source:data,
autoFocus:true,
/*call this function after select value from autocomplete suggestions */
select: function (event, ui) {
$("#lblMsg").html("You selected: " + ui.item.label);
},
/*minLength defines, minimum character in textbox to show suggestions */
minLength: 0,
/*show autocomplete suggestions list on textbox focus.  */
}).focus(function () {
$(this).autocomplete("search", "");
});
});

</script>
</head>

Now, save and run the file in browser and when we start typing the first alphabet, it is matched against a list of the countries defined in our array and the matches get displayed in a drop-down menu attached to the textbox.

Result:


Live Demo (Try it):





If you like this, please share with your friends...



0 comments:

Post a Comment

Subscribe for Latest Update

Popular Posts