jQuery Autocomplete Multiple Fields Using jQuery, Ajax, PHP and MySQL

Posted by & filed under Ajax, HTML5, JQUERY, MYSQL, PHP.

In one of the previous tutorial, I had implemented jQuery autocomplete using jQuery, Ajax, PHP and MySQL. Before continuing this, please refer this following tutorial for complete basics and integration of jQuery autocomplete.

Refer this video tutorial series on jQuery autocomplete right from the scratch : jQuery UI Autocomplete Video Tutorials

Learn jQuery Autocomplete in 3 Minutes

Dynamically Add and Remove Table Rows Using jQuery

jQuery Multiple Fields(Textbox) Autocomplete with Multiple values:

jquery autocomplete integration

jQuery Autocomplete Search using PHP, MySQL and Ajax

Please refer following my latest tutorial on jQuery autocomplete

Invoice System Using jQuery AutoComplete

jQuery Autocomplete Post Tagging System Like In WordPress

In this tutorial I am going to show how to populate multiple textfields using single jQuery autocomplete select. For example I am going search country name on country name textfield using jQuery autocomplete, finally results will show list of country names that matches your search. While selecting country name from any one of the search results, it will populate that corresponding country Number, Country Phone code and Country code will be populated automatically in their respective textfields.

jQuery Autocomplete Mutiple Fields Using jQuery, Ajax, PHP and MySQL

jQuery Autocomplete Mutiple Fields Using jQuery, Ajax, PHP and MySQL

Step 1: Create Your Sample Database, Table and Confguration Files:

Please refer my previous tutorial to create the sample database, tables and php configuration files.

jQuery Autocomplete Search using PHP, MySQL and Ajax

Step 2: Create Your HTML Form for this jQuery Autocomplete:

Using following html script create your HMTL form for jQuery autocomplete.

 <form action="index.php" name="students" method="post" id="students">
    <input type="text" name="countryname[]" id="countryname_1" class="ui-autocomplete-input">
    <input type="text" name="country_no[]" id="country_no_1" class="ui-autocomplete-input">
    <input type="text" name="phone_code[]" id="phone_code_1" class="ui-autocomplete-input">
    <input type="text" name="country_code[]" id="country_code_1" class="ui-autocomplete-input">
 </form>

Please ensure following js files and css are added in your php or html page.

<link rel="stylesheet" href="css/jquery-ui-1.10.3.custom.min.css" />
<script src="js/jquery-1.10.2.min.js"></script>	
<script src="js/jquery-ui-1.10.3.custom.min.js"></script>

Step 3: Write your jQuery Autocomplete Script:

All we need is when user starts to search on country name textfield based on the search, we need to show autocomplete search results. For that we need select country name text field and implement autcomplete method on it.


$(document).on('focus','.autocomplete_txt', handleAutocomplete);

function getId(element){
    var id, idArr;
    id = element.attr('id');
    idArr = id.split("_");
    return idArr[idArr.length - 1];
}
    
function getFieldNo(type){
    var fieldNo;
    switch (type) {
        case 'countryname':
            fieldNo = 0;
            break;
        case 'countryno':
            fieldNo = 1;
            break;
        case 'phone_code':
            fieldNo = 2;
            break;
        case 'country_code':
            fieldNo = 3;
            break;
        default:
            break;
    }
    return fieldNo;
}

function handleAutocomplete() {
    var type, fieldNo, currentEle; 
    type = $(this).data('type');
    fieldNo = getFieldNo(type);
    currentEle = $(this);

    if(typeof fieldNo === 'undefined') {
        return false;
    }

    $(this).autocomplete({
        source: function( data, cb ) {	 
            $.ajax({
                url:'ajax.php',
                method: 'GET',
                dataType: 'json',
                data: {
                    name:  data.term,
                    fieldNo: fieldNo
                },
                success: function(res){
                    var result;
                    result = [
                        {
                            label: 'There is matching record found for '+data.term,
                            value: ''
                        }
                    ];

                    if (res.length) {
                        result = $.map(res, function(obj){
                            var arr = obj.split("|");
                            return {
                                label: arr[fieldNo],
                                value: arr[fieldNo],
                                data : obj
                            };
                        });
                    }
                    cb(result);
                }
            });
        },
        autoFocus: true,	      	
        minLength: 1,
        select: function( event, ui ) {
            var resArr, rowNo;
            
            
            rowNo = getId(currentEle);
            resArr = ui.item.data.split("|");	
            
        
            $('#countryname_'+rowNo).val(resArr[0]);
            $('#countryno_'+rowNo).val(resArr[1]);
            $('#phone_code_'+rowNo).val(resArr[2]);
            $('#country_code_'+rowNo).val(resArr[3]);
        }		      	
    });
}

I had set minLength to 0, so when user start to type his first letter or press space button. It will makes ajax request and brings out the jQuery autocomplete results from MySQL database. You may set jQuery autocomplete minLength based on your need for ex. 2 or 3.

In the jQuery autocomplete success method, I am getting the results and splits the country name and assign it to the label and value object. When user selects his desired result from the list of autocomplete result list, jQuery autocomplete select method is triggered. Where selected result is splited as well as assigned to the Country Number, Country Phone code and Country code textfields.

Step 4: jQuery Autocomplete PHP Script:

Here is jQuery autocomplete PHP configuration file and php script for jQuery autocomplete multifields.

<?php
/*
Site : http:www.smarttutorials.net
Author :muni
*/
define('DB_HOST', 'localhost');
define('DB_NAME', 'autocomplete');
define('DB_USERNAME','root');
define('DB_PASSWORD','');

$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();

php script for jQuery autocomplete for multiple textfields.


<?php
/*
Site : https://smarttutorials.net
Author :muni
 */
require_once 'config.php';

$fieldNo = !empty($_GET['fieldNo']) ? $_GET['fieldNo'] : '';
$name = !empty($_GET['name']) ? strtolower(trim($_GET['name'])) : '';

$fieldName = 'name';

switch ($fieldNo) {
    case 1:
        $fieldName = 'numcode';
        break;
    case 2:
        $fieldName = 'phonecode';
        break;
    case 3:
        $fieldName = 'iso3';
        break;
}

$data = array();
if (!empty($_GET['name'])) {
    $name = strtolower(trim($_GET['name']));
    $sql = "SELECT name, numcode, phonecode, iso3 FROM country where LOWER($fieldName) LIKE '" . $name . "%'";
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row['name'] . '|' . $row['numcode'] . '|' . $row['phonecode'] . '|' . $row['iso3'];
        array_push($data, $name);
    }
}
echo json_encode($data);exit;

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

%d bloggers like this:

Get Instant Script Download Access!