Creating a Chained Select

chained-select-nvidiaThis article is based on the question asked on Web Developer Forum on creating a category tree using select. Also known as chained select.

First, a description of chained select. It is a series of selection using select box where each sub-select depends on the previous selection.

Examples of this kind of chained select is usually encountered when downloading drivers, such as that found in NVIDIA website.

On NVIDIA website, the select boxes are all empty except the first one. While here I am going to create new select box if there is still a sub-selection. It can go on unlimited select box.

Onto the logic and codes:

First, I need to be able to dynamically create the select. For this, I used the code found on StackOverflow. I used the vanilla version. You might go with JQuery version, if you use that.

Once it is done, I simply modify the code to include onClick event on the select element.

The function included in onClick will check if there is still data to create the next select box. If there is, then it will create a new select box.

Very very simple.

Here is the full code:

<html>
 <head>
   <title>chained select</title>
 </head>
 <body>
   <form id = 'myform'>
   </form>
<script type="text/javascript">
 var select1=[];
 select1[0] = "choose one";
 select1[1] = "pc";
 select1[2] = "laptop";

 var selectpc = [];
 selectpc[0] = "choose one";
 selectpc[1] = "dell";
 selectpc[2] = "hp";

 var selectlaptop = [];
 selectlaptop[0] = "choose one";
 selectlaptop[1] = "acer";
 selectlaptop[2] = "hp2";

 var selectpcdell=[];
 selectpcdell[0] = "choose one";
 selectpcdell[1] = "dell 1";
 selectpcdell[2] = "dell 2";
var selecthp=[];
 selecthp[0] = "choose one";
 selecthp[1] = "hp pc 1";
 selecthp[2] = "hp pc 2";
var selectpcdell1=[];
 selectpcdell1[0] = "choose one";
 selectpcdell1[1] = "with GPU";
 selectpcdell1[2] = "without GPU";

 var selecthp2=[];
 selecthp2[0] = "choose one";
 selecthp2[1] = "hp laptop 1";
 selecthp2[2] = "hp laptop 2";
function addInput(divName, choices){
 var newDiv=document.createElement('div');
 var selectHTML = "";
 var choiceselect = "";
 selectHTML="<select onClick='selectClick(this)'>";
 for(i=0; i<choices.length; i=i+1){
 selectHTML+= "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
 }
 selectHTML += "</select>";
 newDiv.innerHTML= selectHTML;
 document.getElementById(divName).appendChild(newDiv);
 }
function selectClick(myselect)
 {
 switch(myselect.value)
 {
 case 'pc':
 addInput('myform', selectpc);
 break;
 case 'dell':
 addInput('myform', selectpcdell);
 break;
 case 'dell 1':
 addInput('myform', selectpcdell1);
 break;
 default:
 }
 }
addInput('myform', select1);
 </script>
</body>
</html>

Note that I created my own selection. Where in reality you would grab them using AJAX call to your database.

Hope you find it useful. Please share the article if you find it useful.