Skip to content
Derek Jones edited this page Jul 5, 2012 · 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 whit 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 its a example the divs and inputbox.

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

<div id="suggestions">
    <img src="&lt;?=config_item('dir_img')?&gt;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->ciudad."</li>";
    
            endforeach;    
        } 

    echo "

  • id ."")'>".$row->ciudad."
  • "; this the echo complete.. for any reason in the tag code here dont appear fine

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

    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