The Idea
You want to ask the user to enter a name in the input text field, so that the moment the user types the first character of a name, a suggestion box will appear that displays all the names beginning with the character typed. You also want the names displayed in the suggestion box to have a hovering effect – so that they become highlighted on moving the mouse pointer over them – and the clicked name to be inserted in the input text field.
Implementation
Let’s create an HTML file that displays a label: ‘Enter userid’ and an input text field. Below the input text field, we create two empty div elements that are assigned the class names: listbox and nameslist respectively. The HTML file may appear as shown below:
The div element of class listbox will be used for displaying a box and the div element nameslist will be used for displaying the names with hovering effect. We define the style rules to be applied to the two div elements in the style sheet file: style.css as shown here:
.listbox { position: relative; left: 10px; margin: 10px; width: 200px; background-color: #000; color: #fff; border: 2px solid #000; } .nameslist { margin: 0px; padding: 0px; list-style:none; } .hover { background-color: cyan; color: blue; }
The jQuery code to now make our suggestion box appear when the user types the first character in the input text field, and to make the clicked name (in the suggestion box) to appear in the input text field automatically, is as shown here:
$(document).ready(function() { $('.listbox').hide(); $('.userid').keyup(function () { var uid = $('.userid').val(); var data='userid='+uid; $.ajax({ type:"POST", url:"autocomplete.php", data:data, success:function(html) { $('.listbox').show(); $('.nameslist').html(html); $('li').hover(function(){ $(this).addClass('hover'); },function(){ $(this).removeClass('hover'); }); $('li').click(function(){ $('.userid').val($(this).text()); $('.listbox').hide(); }); } }); return false; }); });
The script file autocomplete.php, on the server, is designed to send the list of names as response, and it should look like this:
echo '
Check out your site now. Try typing a name begins with 'J'.
Booya! If everything's goes well I believe you will get a pop-up with a list of name begins with 'j'.
Though this is not the best way of generating the autocomplete menu and obviously we will generate the autocomplete menu using data from the database, but I believe you get the idea. I will make another post where I'm going to show how can we can grab the information(data) from the database and fill the autocomplete list with it. Knock me out if you have any question. Till then bye bye.