Skip to content
sajanNOPPIX edited this page Jan 2, 2013 · 16 revisions

Category:Help::TipsAndTricks

Trick for implement easily an Autocomplete Ajax. This requires jQuery!

Advantages!

  • You dont need other plugin for use autocomplete
  • Works with all browsers
  • Faster
  • Customizable with css
  • Easy implementation in CI.

Implementation

In your View:

Put this code for javascript.

function lookup(inputString) {
    if(inputString.length == 0) {
        $('#suggestions').hide();
    } else {
        $.post("http://site/controller/autocomplete/", {queryString: ""+inputString+""}, function(data){
            if(data.length > 0) {
                $('#suggestions').show();
                $('#autoSuggestionsList').html(data);
            }
        });
    }
}

function fill(thisValue) {
    $('#id_input').val(thisValue);
    setTimeout("$('#suggestions').hide();", 200);
}   

Explanation:

You use two funtions:

The first function named "lookup" is call in the the event onKeyUp from the inputbox. in this function you send to the controller the caracters what the user type.

The second function named fill, is call when the user select a item from the list shown for the ajax.

You can modify the number the caracters for go to search, adding to the else the first function (inputString.length > 1 or 2 or ....).

Html objects.

This is a example of the divs and inputbox.

<input name="name" id="id_input" type="text">

<div id="suggestions">
    <img src="<?=config_item('dir_img')?>upArrow.png">
    <div class="autoSuggestionsList_l" id="autoSuggestionsList">    
    </div>
</div>

Controller

In the controller return the result whit an echo, in this echo you print a tag

  • for show the results, you can add the id and the value both.
    function autocomplete()
    {
        $this->load->model('model','get_data');
        $query= $this->get_data->get_autocomplete();
        
        foreach($query->result() as $row):
            echo "<li id='$row->id'>".$row->ciudad."</li>";
        endforeach;    
    } 

    Model

    A query....

    $this->db->select('field');
    $this->db->where('fiedl3',1);
    $this->db->like('field',$this->input->post('queryString'));
    return $this->db->get('table', 10);    

    Example http://yfrog.com/9hscreensnapzp

    Enjoy!

  • Clone this wiki locally