article

Saturday, June 2, 2012

Jquery Ajax auto complete text box

Jquery Ajax auto complete text box

Download



 
<script type="text/javascript" src="jquery-1.2.1.pack.js"></script>
<script type="text/javascript">
 function lookup(inputString) {
  if(inputString.length == 0) {
   // Hide the suggestion box.
   $('#suggestions').hide();
  } else {
   $.post("post.php", {queryString: ""+inputString+""}, function(data){
    if(data.length >0) {
     $('#suggestions').show();
     $('#autoSuggestionsList').html(data);
    }
   });
  }
 }
 function fill(thisValue) {
  $('#inputString').val(thisValue);
  setTimeout("$('#suggestions').hide();", 200);
 }
</script>
<style type="text/css">
 body {
  font-family: Helvetica;
  font-size: 11px;
  color: #000;
 }
 h3 {
  margin: 0px;
  padding: 0px; 
 }
 .suggestionsBox {
  position: relative;
  left: 30px;
  margin: 10px 0px 0px 0px;
  width: 200px;
  background-color: #212427;
  -moz-border-radius: 7px;
  -webkit-border-radius: 7px;
  border: 2px solid #000; 
  color: #fff;
 }
 .suggestionList {
  margin: 0px;
  padding: 0px;
 }
 .suggestionList li {
  
  margin: 0px 0px 3px 0px;
  padding: 3px;
  cursor: pointer;
 }
 .suggestionList li:hover {
  background-color: #659CD8;
 }
</style>
<div>
  <form>
   <div>
    Type your county:
    <br />
    <input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
   </div>
   
   <div class="suggestionsBox" id="suggestions" style="display: none;">
    <img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
    <div class="suggestionList" id="autoSuggestionsList">
      
    </div>
   </div>
  </form>
</div>
//post.php
<?php
 $db = new mysqli('localhost', 'root' ,'ednalan', 'dbname');
 if(!$db) {
  echo 'ERROR: Could not connect to the database.';
 } else {
  if(isset($_POST['queryString'])) {
   $queryString = $db->real_escape_string($_POST['queryString']);
   if(strlen($queryString) >0) {
    $query = $db->query("SELECT value FROM countries WHERE value LIKE '$queryString%' LIMIT 10");
    if($query) {
     while ($result = $query ->fetch_object()) {
      echo '
  • '.$result->value.'
  • '; } } else { echo 'ERROR: There was a problem with the query.'; } } else { } } else { echo 'There should be no direct access to this script!'; } } ?>

    Related Post