2 Combo Box display

Guys do you have solution regarding 2 combo boxes dependent with each other.
Like the STATE AND CITY, when you select a STATE then depending on the state you selected
ONLY CITIES under that will be populated on the 2nd combo box.

Thanks!

P.S. No Jquery please…

You’d need Ajax to do a server side lookup to retrieve the cities to populate the second combo box with (assuming that your visitor chooses a value for the first combo box that you know the cities for). You will probably need some JavaScript to tie the combo box together as not all browsers support combo boxes yet as they were only introduced in HTML 5.

This should do the job.


<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Select Cities</title>
<script type="text/javascript">
//
// initialise shortcuts on page load
var selectObj1, selectObj2; // global
 function init()
  { selectObj1=document.getElementById("select_1");
    selectObj2=document.getElementById("select_2");
    selectObj2.disabled=true; 
  }
// ========== end init() ============== 
// second select box options list
var A= new Array()
A["NSW"]=["Select here ...","Sydney","Newcastle","Dubbo"];
A["Victoria"]=["Select here ...","Melbourne","Portland","Geelong"];
A["Queensland"]=["Select here ...","Brisbane","Gladstone","Cairns"];
//
// global variables
var saveObj=null, indx=null, targetObj=null, selectNo=null;   
// 
 function process(obj,sNumb)
  { // disable unused select boxes 
    if(sNumb==2)
     { selectObj2.selectedIndex="0";
       selectObj2.disabled=true;
     }
   //
   // store selected index   
    indx=obj.options.selectedIndex;
    if(indx==0){ return; }               // invalid selection 
   // ---------
   // save passed parameters for use after timeout deleay   
    saveObj=obj, selectNo=sNumb;     
  // put object items list into next select box after clearing
     targetObj=document.getElementById("select_"+selectNo)
     targetObj.disabled=false;
   // clear any existing options note that this starts from end of list, not beginning  
     for(var i=targetObj.options.length-1;i>-1;i--)
          { targetObj.options[i]=null;  }   
  // build in short delay here to avoid error in Opera browser
      setTimeout("finishOff()",50)
    }
// ----------- 50ms delay here --------   
// called from timeout in function process()
   function finishOff()
    {  var obj=saveObj;    // from global
      // fill selectObj options  
       var i, thisItem=0;                         
      // build options list
      var targArray = A[obj.options[indx].value];   
      //
       for(i=0;i<targArray.length;i++)
         { thisItem=targArray[i];      
          // syntax is new Option("text", "value", isDefaultSelectedFlag, isSelectedFlag)
                    
           targetObj.options[i]=new Option(thisItem,thisItem,false,false);    
         } 
     obj.blur(); 
  }
// ============ end process() ===================
// fires on selecting in second select box
 function finish()
  { if(selectObj2.selectedIndex==0){return; }    // invalid selection    
    alert("You have selected ["+selectObj1.value+"]  ["+selectObj2.value+"]")
  }
// ------------  
//
window.onload=init;
// 
</script>
<style type="text/css">
<!--
.S_any { position:absolute; top:50px; width:100px; text-align:left; }
#S1    { left:10px;  }
#S2    { left:150px; }
select { width:120px; }
-->
</style>
</head>

<body>

<div id="S1" class="S_any">
  <select id="select_1" onchange="process(this,2)">
  <option value="0">Select here ....</option>
  <option value="NSW">NSW</option>
  <option value="Victoria">Victoria</option>
  <option value="Queensland">Queensland</option>
  </select>
</div>
<!-- end S1 -->
<div id="S2" class="S_any">
  <select id="select_2" onchange="finish()">
  <option value="0">Select here ....</option>
  </select></div>
<!- end S2>

</body>

</html>


I agree with felgall and you’ll probably do this with AJAX.

But if you’re after just a javascript solution then this plain vanilla version might help you get started. Works in all the major browser (including opera)


<script type="text/javascript">
            var selData = [
                ['state1','city11','city12','city13','city14'],
                ['state2','city21','city22'],
                ['state3','city31','city32','city33'],
                ['state4','city41','city42','city43','city44','city45']
            ];
            function getCities(idx){
                selCitiesObj.options.length = 0;
                selCitiesObj.disabled = true;
                if(idx == 0){return;}
                for(i=0; i<selData[idx-1].length; i++){
                    var cityOpt = (i == 0)? new Option('Select a city','',false,false) : new Option(selData[idx-1][i],selData[idx-1][i],false,false);
                    selCitiesObj.options[selCitiesObj.options.length] = cityOpt;
                }
                selCitiesObj.disabled = false;
            }
            window.onload=function(){
                var selStateObj = document.getElementById('selState');
                selCitiesObj = document.getElementById('selCities');
                selCitiesObj.disabled = true;
                selStateObj.onchange=function(){getCities(this.selectedIndex);}
                for(i=0; i<selData.length; i++){
                    var stateOpt = new Option(selData[i][0],selData[i][0],false,false);
                    selStateObj.options[selStateObj.options.length] = stateOpt;
                }
            }
        </script>

        <form action="" method="post">
            <select id="selState" name="selState">
                <option value="">Choose a State</option>
            </select>
            <select id="selCities" name="selCities"></select>
        </form>

Neither of those solutions is using combo boxes though - they are just using plain select lists. Here’s the equivalent HTML to use combo boxes.

<form action="" method="post"><div>
            <input type="text" id="selState" name="selState" list="state">
                <datalist id="state">
                <li>Choose a State</li>
                </datalist>
            <input type="text" id="selCity" name="selCity" list="city">
                <datalist id="city">
                </datalist>
</div>       </form>

Yes that’s true, but very often noobies in forums refer to a <select> as a combo box, which it technically isn’t. The disadvantage of using your <datalist> is that it’s a html5 element and so won’t necessarily be supported in all browsers atm. A <select> obviously will and you can of course create the functionality of a true combo box in html4 or xhtml but I didn’t include the code for that, assuming the op was referring to populating a second <select> based on the selection in the first <select> which is a common request for help.

Stephen don’t you think this is a somewhat rigid interpretation of the term “combo box”?

Look at the definition in Wikipedia which is:
“A combo box is a combination of a drop-down list or list box and a single-line textbox, allowing the user to either type a value directly into the control or choose from a list of existing options”.

Your <datalist> suggestion might do something similar, but for most people <select> and <option> tags ARE a combo box. it also seems unwise to recommend a solution which has been introduced only in HTML5 - a development which is not yet finalised, and a tag which is only supported in Firefox and Opera.

I would be interested to know why you prefer the <datalist> over the <select> solution.

For an HTML4 combo box you simply replace the datalist tag with a ul tag and use JavaScript to link the two together to form a combo box. See http://javascriptexample.net/domform11.php for an example.

As that quote from Wilipedia says - a combo box is a combination of an INPUT field with a drop down list. While a drop down list can be inplemented in HTML using select and option you can’t combine it with an input field if you define the drop down list that way. The easiest way to combine the two is to use an input field as the input field half and a list as the dropdown list half - datalist being added in HTML5 so that the combo box can actually be fully defined in the HTML rather than needing JavaScript to implement it.

I realise that the OP was probably meaning a select list when they referred to combo box (which are only confused in HTML because HTML unlike everywhere else did not until HTML 5 actually have a combo box form field) and was simply adding the information about how to define a combo box in case the OP really meant a combo box rather than just a select list. The OP may be used to applications elsewhere that really do have combo box fields as well as select lists.

I apologize for the confusion, well I am referring to <select> tag… Honestly, I am noob in javascript so ajax is alien to me. I need to understand it as simple as possible. so I can advance gradually and learning ajax in the process.

That’s ok, I wasn’t confused :slight_smile:

Post #4 is about as easy as I can make it to start you off with.

In that case I suggest that you give Bulletproof Ajax a good read. I have not found a better resource for learning about Ajax stuff so far.

Thanks man… I will try it out.

It really works, can I try having a dynamic content via PHP?
Thanks… This is a start.

you sound surprised :lol: :slight_smile:

This is where it will get a little more complicated. You could have all the state/city data stored in a database on the server or just in an array in a server side script. Typically, this type of data (like product categories and their products) would be stored in a database.

You can populate the second <select> with dynamic data with or without ajax, just depends on whether you want a page refresh (without ajax) or not. The normal process would be to send an ajax request to a server side script to retrieve the information in the database for the option selected in the first <select>. The server side script then sends back to the ajax function the requested information. The ajax function then deletes the current options in the second <select> and inserts options based on the received information from the server.

Have a go at it (there is heaps of info on google regarding ajax) and if you get stuck post back with your code.

Ajax is really neat since you can not see the whole page to be loaded again… but I just really need the the-whole-page-will-be-refreshed-solution in javascript, thanks for the help. I will post it again if ever I bumped into problems (which Im sure I will) Thank you everyone