I want to imitate Google suggest with the following code, which means:
step 1: When user types in search box, the query string will be processed by a server php file and query suggestion string is returned(using Ajax object).
step 2:When user clicks on a query suggestion, it will fill into the search box (autocomplete).
Step 1 is achieved while step 2 is not. I think the problem lies in the .click() method (I use .live() later, but it's still not working). My intention is to use .live() or .click() binding a onclick event to the dynamically created <li>
element. Any idea?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script src="jquery-1.4.2.js">
</script>
<style>
#search,#suggest,ul,li{margin: 0; padding:0; width: 200px;}
ul{ list-style-type: none;}
.border{border: solid red 1px; }
</style>
<p>My first language is:</p>
<input type="text" width="200px" id="search" onkeyup="main(this.value)" value="" />
<ul id="suggest"></ul>
<script type="text/javascript">
$(function main(str)
{ //binding any forthcoming li element click event to a function
$('li').live('click', function(){ $("#search").val(array[i]);});
//setup Ajax object
var request=new XMLHttpRequest();
request.open("GET","language.php?q="+str,true)
//core function
request.onreadystatechange=function()
{
if ( request.readyState==4 && request.status==200)
{ if (str=="") {$('li').remove(); $('ul').removeClass('border');return;}
$('li').remove();
reply=request.responseText.split(",");
for (i=0;i<reply.length;i++)
{
//create HTML element of <li>
$('#suggest').append($('<li>',{id: 'li'+i, html: reply[i]}));
//style ul
$('ul').addClass('border');
}
}
}
request.send();
})
</script>
PHP:
<?php
$q=$_GET[q];
$a[]='english';
$a[]='chinese';
$a[]='japanese';
$a[]='eeeeee';
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>