JQuery

Autocomplete TextBox with JQuery



In this tutorial i will explain how you can build an Ajax based autocomplete application for text boxes in your website using JQuery and PHP
I assume the readers have basic knowledge about JQuery and knows how to use JQuery library

If not please read  Introduction Here

Here is the screen shot

demojq.jpg

SO Lets start.Here is the javascript code which you need to insert into your html head section
Javascript Section

<script src="jquery-1.2.1.pack.js" type="text/javascript"></script><script type="text/javascript">
function lookup(inputString) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $(‘#suggestions’).hide();
    } else {
        $.post("shf.php", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {
                $(‘#suggestions’).show();
                $(‘#autoSuggestionsList’).html(data);
            }
        });
    }
} // lookup

function fill(thisValue) {
    $(‘#inputString’).val(thisValue);
   $(‘#suggestions’).hide();
}

</script>

Javascript Explanation

The code above takes the user input in the text box and passes the user input to a php file  named  shf.php  where the suggestions data are generated and displayed.
Obviously what we need to do next is to invoke the above javascript when user types something on the text box.Lets see how this can be done

Here is the HTML Code.Insert the code below to the body section of your page
HTML Section

<div>
       <div>

      Type your Text(for the demo):
<input size="30" id="inputString" onkeyup="lookup(this.value);" type="text" />

    </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>

</div>

You can also do some formatting using CSS.Insert the code to the head section of your page

Here is  the code
CSS Section

<style type="text/css">
.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>

ANd here comes the php back end

shf.php

<?php

 

// PHP5 Implementation - uses MySQLi.

// mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');

$db = new mysqli('localhost', 'root' ,'', 'shefeek');

 

if(!$db) {

// Show error if we cannot connect.

echo 'ERROR: Could not connect to the database.';

} else {

// Is there a posted query string?

if(isset($_POST['queryString'])) {

$queryString = $db->real_escape_string($_POST['queryString']);

 

// Is the string length greater than 0?

 

if(strlen($queryString) >0) {

// Run the query: We use LIKE '$queryString%'

// The percentage sign is a wild-card, in my example of countries it works like this...

// $queryString = 'Uni';

// Returned data = 'United States, United Kindom';

 

// YOU NEED TO ALTER THE QUERY TO MATCH YOUR DATABASE.

// eg: SELECT yourColumnName FROM yourTable WHERE yourColumnName LIKE '$queryString%' LIMIT 10

 

$query = $db->query("SELECT distinct url FROM seotoolskit WHERE url LIKE '$queryString%' LIMIT 10");

 

 

if($query) {

// While there are results loop through them - fetching an Object (i like PHP5 btw!).

while ($result = $query ->fetch_object()) {

// Format the results, im using <li> for the list, you can change it.

// The onClick function fills the textbox with the result.

 

// YOU MUST CHANGE: $result->value to $result->your_colum

echo '<li onClick="fill(\''.$result->url.'\');">'.$result->url.'</li>';

}

} else {

echo 'ERROR: There was a problem with the query.';

}

} else {

// Dont do anything.

} // There is a queryString.

} else {

echo 'There should be no direct access to this script!';

}

}

?>

I guess not much explanation is needed on the above code because enough comments are provided..Please comment on if you need more assistance

Related posts:

  1. Jquery – Chapter 2 .Show/Hide Div tag In this chapter i will explaining how you can show and hide the contents inside a div tag on a mouse click using jquery Here...
  2. JQuery – Chapter 3 . Loading Update spinner for image loading In this chapter i will explain you how you can bring a spinner or any other image when it takes time to load a...
  3. Jquery Introdution – Chapter 1 JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery...

Thanks for reading my blog. If you like what I write, why not subscribe to my feed?

If you are busy, I can send the latest post to your email. Just subscribe to my email updates.

 

Enter your email address:

Delivered by FeedBurner

Discussion

No comments for “Autocomplete TextBox with JQuery”

Post a comment