Blog > detail

Just my tiny mind

Javascript Autocomplete

26-2-2012 Admin General 2 Comments

Javascript Autocomplete

Javascript Autocomplete is a javascript that can give sugestion to the user when seraching value in the text area. Then user can chose among the given sugestions. Because we also use database then we will need Jquery and PHP to access the data.

Lets just jump to the Javascript Autocomplete code.

First the HTML one (index.html):

<script language="javascript" src="jquery.js"></script>

<script language="javascript" src="engine.js"></script>

<input type="hidden" id="choose" value="0" />

<div id="ch0" style="display:none"></div>

<input type="text" onblur="check(this.value)" id="search" onkeyup="check(this.value);"/>

<div id="result"></div>

Second the Javascript code (engine.js):

function check(val){

if(event.keyCode == 40||event.keyCode == 38){



$.post("test.php",{val:val} , function(data){document.getElementById("result").innerHTML =data;});

document.getElementById('choose').value = 0;



function choose(evnt){

chs = document.getElementById('choose').value;

chs = parseInt(chs);

if(evnt == 40){

chs2 = chs+1;


chs2 = chs-1;

if(chs < 0)chs = 0;


selc = document.getElementById('ch'+chs2);

selcold = document.getElementById('ch'+chs);

if(selc){ = "blue";

document.getElementById('search').value = selc.innerHTML; = "white";





document.getElementById('choose').value = chs2;


Last is the PHP file (test.php)

$link = mysql_connect('localhost', 'root', '');

if (!$link) {



$dbname = 'member';


$val = $_POST['val'];

if($val == '') break;

$q = "select name from client where name like '$val%'";

$e = mysql_query($q);


while($r = mysql_fetch_array($e)){


echo '<div id="ch'.$i.'">'.$r['name'].'</div>';


When you type something in the textbox, then Javascript Autocomplete will search posible match for the inputed value. When you pres the down/up button, the Javascript Autocomplete will navigate to the sugestions.

Javascript Autocomplete Javascript Autocomplete Javascript Autocomplete

Javascript Autocomplete Javascript Autocomplete Javascript Autocomplete

Javascript Autocomplete

word word

Javascript Autocomplete

Javascript Autocomplete

Javascript Autocomplete