Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 16 revisions

Trick for implement easily an Autocomplete Ajax.

Advantages!

You dont need other plugin for use autocomplete works whit all browsers faster customizable whit css easy implementation in CI.

Implementation

In your View:Put this code for javascript. [code] 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);
}   

[/code] 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.

Html objects. This its a example the divs and inputbox.

[code] <input name="name" id="id_input" type="text>

[/code]

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.

    [code]function autocomplete() {
    $this->load->model('model','get_data'); $query= $this->get_data->get_autocomplete();

        foreach($query->result() as $row):
        
        echo "<li>id ."\")'>".$row->field."</li>";
    
        endforeach;    
    } 
    

    [/code]

    Necessary use ("" and "") if the return is a string, for handled the white spaces in javascript.. example "house here"

    Model A query.... [code] $this->db->select('field'); $this->db->where('fiedl3',1); $this->db->like('titulo',$this->input->post('queryString')); return $this->db->get('table', 10);
    [/code]

    Enjoy!

  • Clone this wiki locally