Autocomplete Textbox in CodeIgniter using jQuery UI

The Autocomplete textbox helps users to find and select the value from pre-populated values list. It provides suggestions while user type in the input field. Generally, the autocomplete textbox is used for search input field where the user allows to input the pre-stored data. Using jQuery UI, you can easily implement an autocomplete textbox on the website. The jQuery UI Autocomplete plugin is an instant way to add autocomplete feature to the input text field. This plugin converts the input fields into an autocomplete that receives input from the user. When typing in the autocomplete field, this plugin start searching for values that match and list them to choose from.

In the web application, autocomplete textbox populate the suggestions from the database and allow the user to select. Like PHP you can easily add jQuery UI autocomplete in CodeIgniter with MySQL database. In this tutorial, we will show you how to add autocomplete feature to textbox in CodeIgniter using jQuery UI.

The example code will demonstrate the autocomplete functionality by adding the skills autocomplete search textbox in CodeIgniter.

Create Database Table

To store the skills data you need to create a table in the database. The following SQL creates a skills table with some basic fields in the MySQL database.

CREATE TABLE `skills` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `skill` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Controller (Skills.php)

The Skills controller has 3 functions, __construct(), index(), and autocompleteData().

  • __construct() – Loads the Skill model to retrieve the skills data from the database.
  • index() – Loads the view to display the skills search input field.
  • autocompleteData()
    • Fetched the skills data from the database based on the search term.
    • Generate an array with id and value element.
    • Return the skills data as a JSON encoded array.
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class 
Skills extends CI_Controller
{
    function 
__construct() {
        
parent::__construct();
        
// Load skill model
        
$this->load->model('skill');
    }
    
    public function 
index(){
        
// Load the view
        
$this->load->view('skills/index');
    }
    
    function 
autocompleteData() {
        
$returnData = array();
        
        
// Get skills data
        
$conditions['searchTerm'] = $this->input->get('term');
        
$conditions['conditions']['status'] = '1';
        
$skillData $this->skill->getRows($conditions);
        
        
// Generate array
        
if(!empty($skillData)){
            foreach (
$skillData as $row){
                
$data['id'] = $row['id'];
                
$data['value'] = $row['skill'];
                
array_push($returnData$data);
            }
        }
        
        
// Return results as json encoded array
        
echo json_encode($returnData);die;
    }
}

Model (Skill.php)

The getRows() function of Skill model, fetch the data from skills table based on the conditions and returns data as an array.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class 
Skill extends CI_Model{
    function 
__construct() {
        
$this->dbTbl 'skills';
    }
    
    
/*
     * Get rows from the skills table
     */
    
function getRows($params = array()){
        
$this->db->select("*");
        
$this->db->from($this->dbTbl);
        
        
//fetch data by conditions
        
if(array_key_exists("conditions",$params)){
            foreach (
$params['conditions'] as $key => $value) {
                
$this->db->where($key,$value);
            }
        }
        
        
//search by terms
        
if(!empty($params['searchTerm'])){
            
$this->db->like('skill'$params['searchTerm']);
        }
        
        
$this->db->order_by('skill''asc');
        
        if(
array_key_exists("id",$params)){
            
$this->db->where('id',$params['id']);
            
$query $this->db->get();
            
$result $query->row_array();
        }else{
            
$query $this->db->get();
            
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
        }

        
//return fetched data
        
return $result;
    }
}

View (skills/index.php)

The jQuery UI is required to enable the autocomplete feature. Include the jQuery and jQuery UI library first.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

Specify the element ID where you want to enable the autocomplete feature. Also, you need to define a local or remote source to pull the data for auto-suggestions. Since autocompleteData() method of Skills controller retrieve the autocomplete data, the respective URL needs to be specified in the source option of autocomplete() function.

<script>
$(function() {
    $("#skill_input").autocomplete({
        source: "<?php echo base_url('skills/autocompleteData'); ?>",
    });
});
</script>

Initially, an input textbox is provided to enter the skill. When the user starts typing in the textbox, the skills will be fetched from the database based on the search term and suggestions are listed under the textbox. By selecting the skill from the suggestions list, the respective skill value will be set to the input text filed.

<div class="auto-widget">
    <p>Your Skills: <input type="text" id="skill_input"/></p>
</div>

Replace Input Value with ID

By default, after the form submission, the item value will be sent as autocomplete input field value. But, most cases the id of the selected item needs to be is submitted in the form. Using select event, you can replace the input field value with item ID.

$(function() {
    $("#skill_input").autocomplete({
        source: "<?php echo base_url('skills/autocompleteData'); ?>",
        select: function( event, ui ) {
            event.preventDefault();
            $("#skill_input").val(ui.item.id);
        }
    });
});

Autocomplete textbox using jQuery, PHP and MySQL

Autocomplete Widget Configuration Options

jQuery UI Autocomplete plugin provides various options to customize the Autocomplete plugin functionality. Some useful configuration options are given below.
source – Required. The source must be specified from where the data will be fetched for suggestions. You can specify the local or remote source.

  • Local source: An array can be used for local data. [ "Choice1", "Choice2" ] OR [ { label: "Choice1", value: "value1" }, { label: "Choice2", value: "value2" }, ... ]
    $( ".selector" ).autocomplete({
        source: [ "PHP", "Python", "Ruby", "JavaScript", "MySQL", "Oracle" ]
    });
    
  • Remote source: The URL can be used for a remote source that will return JSON data. http://codexworld.com
    $( ".selector" ).autocomplete({
        source: "http://codexworld.com"
    });
    

minLength – Optional (Default 1). The minimum number of characters that must type before the search is performed.

$( ".selector" ).autocomplete({
    minLength: 5
});

select( event, ui ) – Triggered when a value is selected from the suggestions.

$( ".selector" ).autocomplete({
    select: function( event, ui ) {}
});

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up