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

Category:Help::TipsAndTricks

Trick for implement easily an Autocomplete Ajax. [b]This requires jQuery![/b]

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.

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 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->ciudad."</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('field',$this->input->post('queryString')); return $this->db->get('table', 10);
    [/code]

    Example http://yfrog.com/9hscreensnapzp

    Enjoy!

  • Clone this wiki locally