<

[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x

Using a drop down box to populate a second drop down box

Published on
5,688 Points
2,088 Views
1 Endorsement
Last Modified:
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX.

The logical flow for the problem should be:
  1. Write an event handler for the first drop down box to get the user's selections.
  2. Send the user input to the server
  3. At the server, retrieve the data from the client side and process it; then send the result to client side.
  4. At the client, use Javascript to parse the server response and update the other drop down box.


Write an event handler for the first drop down box to get the user's selections:

It sounds difficult. What is an "event handler"?  In fact, every user action performed on the web page triggers an event. To handle those events, we need to write a Javascript function, and we call these javascript functions "event handlers". To handle the user's selection of an item in drop-down box, we need to capture the onchange event. Here is a sample code:
 
 <select id=type name="type" onchange="updateData(this)">

Open in new window


The above code means that a function named "updateData" would be triggered when user selects an item from this drop down box. Here the variable "this" means the dropdown box itself. Let's see what happens in the "updateData" function:
function updateData(dropDownBox)
{
  var value=dropDownBox.options[dropDownBox.selectedIndex].value;
  if (value!="") //Ensure no empty value is submitted to server side
  {
    jQuery.post("getResult.php","type="+value,updateNumber);
  }
}

Open in new window


Send the user input to the server

The statement:

var value=dropDownBox.options[dropDownBox.selectedIndex].value;

Open in new window

retrieves user input from the first drop down box. The following statement mean user input is sent to server side php script "getResult.php".
 
jQuery.post("getResult.php","type="+value,updateNumber);

Open in new window

where, we use the Jquery lib to simplify the sending data to server process. The second parameter is the format of a normal query string and the third parameter is a function that processes the server response.
 

At the server, retrieve the data from the client side and process it; then send the result to client side:

The server side program in our case is "getResult.php". For demonstration purposes we do not connect to a database; we just use the user input to generate a different result and then send that to client.

<?php
	$type=htmlspecialchars($_POST["type"]);
	if ($type=="1")
	{
		echo "1-one\n";//Ends-with \n for client side getting data from server side response
		echo "3-three\n";//Ends-with \n for client side getting data from server side response
		echo "5-five\n";//Ends-with \n for client side getting data from server side response
		echo "7-seven\n";//Ends-with \n for client side getting data from server side response
	}
	else
	{
		if ($type=="0")
		{	echo "2-two\n";//Ends-with \n for client side getting data from server side response
			echo "4-four\n";//Ends-with \n for client side getting data from server side response
			echo "6-six\n";//Ends-with \n for client side getting data from server side response
			echo "8-eight\n";//Ends-with \n for client side getting data from server side response
		}
	}		
?>

Open in new window


At the client, use Javascript to parse the server response and update the other drop down box.

As described above, we need to specify a function that processes the server response and updates the other drop down box.
 
jQuery.post("getResult.php","type="+value,updateNumber);

Open in new window


So, we need to write a Javascript function named "updateNumber" to get the job done.
function updateNumber(data)
      {
        var numberData=jQuery.trim(data).split("\n");//split server side response by "\n"
        var number=document.getElementById("number");
        $("#number").empty();                       //empty the 2nd drop down box  
        for (i=0;i<numberData.length;i++)
        {
          value=numberData[i].split("-")[0];//get value from server response 
          text=numberData[i].split("-")[1]; //get text from server response 
          option=new Option(text,value);    //for better IE compatibility
          number.options[i]=option;      
        }
      }

Open in new window

The first two lines of the function parses server response and the third line empties the target drop down box; the for loop is adding options to the target drop down box.

I have attached the sample code for your reference.
php-ajax.zip
1
Comment
Author:cstsang
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
0 Comments

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Join & Write a Comment

The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…
Suggested Courses

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month