rss

Creating a dynamic select menu

17 Apr, 2008 Navigation

Image by: leunix

I think more of an explanation is required on the title of this post to properly convey what we’re going to accomplish here. We’re going to setup 2 form selects. The 2nd select menu will be dynamically populated based on the selection made in the first drop down. Practically, lets say you want a user to choose from a list of main categories, and then use the second select to choose a sub category of the category chosen in the first select. Make sense? Cool.. here’s how…

Here’s a demo of what we’re going to do.

Firstly, you need the form that will generate the select menu made up of main categories. In this case, I’ve chosen to manually create this list, but you can of course use a bit of creativity to generate this list dynamically too.

<form method="post"><input type="hidden" name="phpMyAdmin" value="01d7dd3a1764f33b9145cd20ad99db24" />
 <select name="country" onchange="htmlData('<? bloginfo('template_directory'); ?>/city.php', 'ch='+this.value)" />
 <option value="#">-Select-</option>
 <option value="Botswana">Botswana</option>
 <option value="EasternCape">Eastern Cape</option>
 <option value="FreeState">Free State</option>
 <option value="GardenRoute">Garden Route</option>
 <option value="Gauteng">Gauteng</option>
 <option value="KwazuluNatal">Kwazulu Natal</option>
 <option value="LimpopoProvince">Limpopo Province</option>
 <option value="Mpumalanga">Mpumalanga</option>
 <option value="Namibia">Namibia</option>
 <option value="NorthWestProvince">North West Province</option>
 <option value="NorthernCape">Northern Cape</option>
 <option value="Other">Other</option>
 <option value="WesternCape">Western Cape</option>
 </select>

You notice this:

<select name="country" onchange="htmlData('<? bloginfo('template_directory'); ?>/city.php', 'ch='+this.value)" />

You’ll now create a file called city.php (or whatever you like – just change the file name in the above select menu to the name of your file) and inside this file you’re going to have the menu’s that will be inserted into the second select menu depending on what is chosen in the first menu. We’ll get to the contents of this file in a second…

Right below the first form that has your main category select menu, you add the second form that contains the select that will be dynamically created. Note that the select menu in this form contains a wrapping div that is used in the Javascript to dynamically populate it.

<form action="<?php echo get_option('home'); ?>/?cat=" method="get">
 <div id="txtResult"> <select name="cat"><option></option></select> </div>
 <input type="submit" name="submit" value="Search" />
</form>

Ok, now you can populate your city.php file with the options for the second, dynamically populated select menu. My file looks like this:

<? if ($_GET['ch'] == 'Botswana') { ?>
<?php wp_dropdown_categories('child_of=33&name=cat'); ?>

<? } if ($_GET['ch'] == 'EasternCape') { ?>
<?php wp_dropdown_categories('child_of=24&name=cat'); ?>

<? } if ($_GET['ch'] == 'FreeState') { ?>
<?php wp_dropdown_categories('child_of=30&name=cat'); ?>

<? } if ($_GET['ch'] == 'GardenRoute') { ?>
<?php wp_dropdown_categories('child_of=25&name=cat'); ?>

<? } if ($_GET['ch'] == 'Gauteng') { ?>
<?php wp_dropdown_categories('child_of=26&name=cat'); ?>

<? } if ($_GET['ch'] == 'KwazuluNatal') { ?>
<?php wp_dropdown_categories('child_of=31&name=cat'); ?>

<? } if ($_GET['ch'] == 'LimpopoProvince') { ?>
<?php wp_dropdown_categories('child_of=28&name=cat'); ?>

<? } if ($_GET['ch'] == 'Mpumalanga') { ?>
<?php wp_dropdown_categories('child_of=27&name=cat'); ?>

<? } if ($_GET['ch'] == 'Namibia') { ?>
<?php wp_dropdown_categories('child_of=32&name=cat'); ?>

<? } if ($_GET['ch'] == 'NorthWestProvince') { ?>
<?php wp_dropdown_categories('child_of=29&name=cat'); ?>

<? } if ($_GET['ch'] == 'NorthernCape') { ?>
<?php wp_dropdown_categories('child_of=23&name=cat'); ?>

<? } if ($_GET['ch'] == 'Other') { ?>
<?php wp_dropdown_categories('child_of=114&name=cat'); ?>

<? } if ($_GET['ch'] == 'WesternCape') { ?>
<?php wp_dropdown_categories('child_of=22&name=cat'); ?>

<?php } ?>

For each of these entries, you should change the child_of value. Basically each of these commands is creating a select menu that contains the child categories of the category I choose in the first select menu.

Now your form content is ready. All thats left to do, is power it up with a bit of Javascript. Call this script in your header.

// select box
function GetXmlHttpObject(handler)
{
 var objXMLHttp=null
 if (window.XMLHttpRequest)
 {
 objXMLHttp=new XMLHttpRequest()
 }
 else if (window.ActiveXObject)
 {
 objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
 }
 return objXMLHttp
}

function stateChanged()
{
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("txtResult").innerHTML= xmlHttp.responseText;
 }
 else {
 //alert(xmlHttp.status);
 }
}

// Will populate data based on input
function htmlData(url, qStr)
{
 if (url.length==0)
 {
 document.getElementById("txtResult").innerHTML="";
 return;
 }
 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 }

 url=url+"?"+qStr;
 url=url+"&sid="+Math.random();
 xmlHttp.onreadystatechange=stateChanged;
 xmlHttp.open("GET",url,true) ;
 xmlHttp.send(null);
}

And that’s that.

Tweak it all up to suit your category names and ID’s and you’ll be good to go. Let me know if you’ve implemented this and how it worked for you! :)

154 Comments

  1. Если кому-то интересно, можете почитать, как мы вдвоем с мужем построили свой домик.
    l [url – http://www.okna-balkony.ru/otchet_domik.htm
    Остекление балконов мытищи

  2. Интересные предложения продажи офисов
    на веб ресурсе бесплатных объявлений по недвижимости Киевской области
    М2metr2.kiev.ua.
    Приглашаем на наш портал риелторов

  3. I am really thankful to the holder of this website who has shared this enormous post at at this time.

  4. Excellent blog here! Additionally your website quite a bit up fast! What web host are you using? Can I am getting your affiliate hyperlink on your host? I want my website loaded up as quickly as yours lol

Leave a Reply

About The WordPress Guru

Over the last 4 or 5 years, I’ve been digging into the Wonders of WordPress. From the days when the Classic theme was the shizz until now, WordPress has gone from strength to strength both as the blogging platform of choice for many big players and as a CMS with...

Learn more »