Selasa, 30 Oktober 2012

JQUERY: Making a basic autocomplete field

An autocomplete is beautifull thing that is widely implemented by a developer in their web project. For example to input a name to the input field that is already in the database. Basicaly this method (autocomplete) is veri simple, first we have to get what is inputed (typed) to the input field, every user press a letter we catch and we send this letter to the php script and the php will query to the database according to the letter typed by the user. Query result then encoded to the JSON format and returned to the AJAX request, now jquery will format this AJAX response to display in the page. Here is the basic code:



1. Create an input field in the page:

<input id="search-name" type="text" /><br />
<ul id="container"></ul>



2. Write jquery script to handle every keyup event to the text field:
$('#search-name').bind('keyup',function(){
    var letter = $(this).val();
    $.get('processor.php',{q:letter},function(data){
        var a = $.parseJSON(data);
        var list ='


  • ';

  •         $.each(a,function(i){
                list += '


  • '+a[i]+'
  • ';
            });
    list += '
    '; $('ul#container').append(list);
        });
    });
    3. Create processor.php, this file use to query to the database according to the user typed text – please use your lovely script for this step  4. You have to format #container for better display, use position: absolute and adjust with it’s left and top value.5. Last, give a script event for onfocus and onblur event to the input field (we do not want to display the list forever event if we leave this input field, right?!?)
    Thank’s to read. This is only a consept you have to improve your code to get better autocomplete

    Tidak ada komentar:

    Posting Komentar