There are times when you prompt your user with two autocomplete input boxes where one depends on the information entered into the first box. For example, the user selects a sport “Basketball” and the second box you choose a team “Milwaukee Bucks”, another could be the first box you select “Football” and the second box autocompletes only NFL football teams. The values that you load in the second box depend on the selection of the first box. There are three options on how to do this:

  1. Load ALL possible values right away for the second box, and have them all available for the user to select. This would be bad user experience because there would be way too many options.

  2. Load ALL possible values into an array and run a filter on the array when the user enters their information into the first box. This is a viable option, but I have a feeling it would take longer than the next method to do the searching and sorting of the array, however, the last method is much more reasonable and more dynamic.

  3. Make an AJAX call using the built in JQuery AJAX function to load all the viable options into a simple array and have it load up before the user enters the box. This tutorial will show you how to do this method.

Preface: I will be sending an AJAX request to a php file that returns all the autocomplete options for the second input box. I believe you can also use the JQuery POST function and set the return to JSON, but I haven’t explored these options. There could also be a variety of other ways to do this along with a variety of more efficient options. Please leave any ideas, critiques, etc in the comment section for others to learn!

We will be using the Professional Sports and Professional Sports team example for this tutorial.

Prerequisites: Must have JQuery and JQuery UI autocomplete function included on the web page, a running PHP web server, and a javascript file where you can add custom functions to.

Step 1: Create your two input boxes

Sport: <input type="text" id="sport" name="sport"></input>
Sports Team: <input type="text" id="sportsTeam" name="sportsTeam"></input>

Step 2: Add the JQuery function for the first box’s autocomplete options

$(function() {
    availableSports = ["Basketball","Football","Baseball"];
  $("#sport").autocomplete({
      source: availableSports
  });
});

What this does is binds the autocomplete function and values to the input id of “sport”. When the user types “Bas” into the box, a drop down below the box will prompt them with either “Basketball” or “Baseball”. The magic comes when they select a sport, and the next drop down matches with only the teams of the sport.

Step 3: Add the sportsTeams.php file in the appropriate location on your web server

This file must be able to be accessed from your JQuery AJAX call.

Step 4: Build up the sportsTeams.php file

There are a variety of ways to get this information. You could load the information from a database, have pre-defined arrays, etc. For the sake of this example I will use pre-defined arrays, populated with 3 teams to get a feel for how the application should work.

*You can use the php array() function as well;

<?php
  //Gets the sports team from the super-global POST that gets sent along from the AJAX call.
  $sport = $_POST["sport"];

  //Defines the basketball team array.
  $basketball[0] = "Milwaukee Bucks";
  $basketball[1] = "Chicago Bulls";
  $basketball[2] = "Minnesota Timberwolves";

  //Defines the football team array.
  $football[0] = "Green Bay Packers";
  $football[1] = "Chicago Bears";
  $football[2] = "Minnesota Vikings";
  //Defines the baseball team array.
  $baseball[0] = "Milwaukee Brewers";
  $baseball[1] = "Chicago Cubs";
  $baseball[2] = "Chicago Whitesox";
  //Defines an empty variable that will return the javascript array.
  $teams = "";
  switch($sport){
    case "Basketball":
        $teams = generateAutocompleteArray($basketball);
    break;

    case "Football":
        $teams = generateAutocompleteArray($football);
    break;

    case "Baseball":
        $teams = generateAutocompleteArray($baseball);
    break;
  }
  //Returns the teams in the appropriate javascript array format.
  echo $teams;
  //Function converts PHP array a string where it can be split into an array easily.
  function generateAutocompleteArray($teamArray){
    $jsTeamArray = "";

    $teamCount = count($teamArray);
    for($i=0; $i<$teamCount; $i++){
        $jsTeamArray.= $teamArray[$i].',';
    }
    //Removes the remaining comma so you don't get a blank autocomplete option.
    $jsTeamArray = substr($jsTeamArray, 0, -1);

    return $jsTeamArray;
  }
?>

Step 5: Add the function to perform the JQuery AJAX call to the PHP file.

function loadSportsTeams(){
    //Gets the name of the sport entered.
    var sportSelected= $("#sport").val();
    var teamList = "";
    $.ajax({
            url: 'sportsTeams.php',
            type: "POST",
            async: false,
            data: { sport: sportSelected}
     }).done(function(teams){
        teamList = teams.split(',');
     });
    //Returns the javascript array of sports teams for the selected sport.
  return teamList;
}

What this does is gets the name the name of the sport that the user entered into the input box. This will automatically have a pre-defined format because the autocomplete is already set for this input box, so the user should select from the drop down. However, there should be some error checking to make sure the user DOES select a sport from the drop down and not enter a sport that isn’t accounted for (unless this fits the use-case of the application). The function then submits an AJAX call to the PHP file and loads the teamList which will become the autocomplete source variable. It is important to set the async to “false” in this case because you don’t want the function to return the null teamList. The team list variable must be populated before the function returns anything.

Step 6: Add the function to set the autocomplete options to the input box

function autocompleteSportsTeams(){
  var teams = loadSportsTeams();
  $("#sportsTeams").autocomplete({
    source: teams
  });
}

What this does is begins to tie everything together. It calls the function to load up all of the sports teams, based off of the user selection. It then sets the auto-complete function’s source variable to the teams that are returned from the file. We are done with most of the process, we just have to link it all together.

Step 7: Add an action handler to the first input box to populate the second input box’s autocomplete options

This can be done in one of two ways. Either with an onblur or onfocus event. For this example we will use the onblur. Once the user leaves the first input box, we will run the javascript function autocompleteSportsTeams(), which will populate the second input box’s autocomplete options.

Sport: <input type="text" id="sport" name="sport" onblur="autocompleteSportsTeams()"></input>

There we go! You now have a dynamic auto complete that generates the options based on the first input box’s value. Like I mentioned earlier there are other ways of accomplishing the same task, however, this one works pretty efficiently. To add more functionality, instead of having a hard-coded array of items, in our case sports teams, we can throw in SQL to read from a database based on what the user enters.

Download Test Files!

*Must have working PHP install!