Following code shows live search box. But it does not disappear when clicked on page anywhere or pressing escape key.
How to hide search result when clicked anywhere or pressed escape key?
index.html
<script type="text/javascript" src="jquery.js"></script>
</script>
$(document).ready(function(){
$(".search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{}
else
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}return false;
});
});
</script>
<div id="jquery-live-search">
<form method="post" action="Search.php">
<p>
<label>
Enter search terms<br />
<input type="text" class="search" id="searchbox" name="searchword"/>
<div id="display">
</div>
</label>
<input type="submit" value="Go" />
</p>
</form>
</div>
search.php
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=
mysql_query("select * from members where firstname like '%$q%' or lastname like '%$q%' order by member_id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$fname=$row['firstname'];
$lname=$row['lastname'];
$img=$row['img'];
$country=$row['country'];
$re_fname='<b>'.$q.'</b>';
$re_lname='<b>'.$q.'</b>';
$final_fname = str_ireplace($q, $re_fname, $fname);
$final_lname = str_ireplace($q, $re_lname, $lname);
?>
<div class="display_box" align="left">
<img src="user_img/
<?php echo $img; ?>" />
<?php echo $final_fname; ?>
<?php echo $final_lname; ?><br/>
<?php echo $country; ?>
</div>
<?php
}
}
else
{}
?>
CSS
*{margin:0px}
#searchbox
{
width:250px;
border:solid 1px #000;
padding:3px;
}
#display
{
width:250px;
display:none;
float:right; margin-right:30px;
border-left:solid 1px #dedede;
border-right:solid 1px #dedede;
border-bottom:solid 1px #dedede;
overflow:hidden;
}
.display_box
{
padding:4px;
border-top:solid 1px #dedede;
font-size:12px;
height:30px;
}
.display_box:hover
{
background:#3b5998;
color:#FFFFFF;
}