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>

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" />

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 {

// Will populate data based on input
function htmlData(url, qStr)
 if (url.length==0)
 if (xmlHttp==null)
 alert ("Browser does not support HTTP Request");

 xmlHttp.onreadystatechange=stateChanged;"GET",url,true) ;

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! :)


  1. I’ve read several good stuff here. Certainly price bookmarking for revisiting.
    I wonder how so much attempt you set to make such a fantastic informative web site.

  2. The yelllowpages usually offer address and contact details of the personal
    injury lawyers, on the other hand it is also possible to locate them from with a little research in the World Wide
    Web. Your lawyer should be more than happy to recommend a personal
    injury attorney that he knows from school or from other situations
    that have arisen through his career. Tax attorneys also negotiate with the tax
    authorities for a compromise to settle back taxes.

  3. Fabuła zbliżona każdemu, rekomenduję lekturę

  4. Dorset England boasts chalk stacks called ‘Old Harry Rocks.
    Epcot: Epcot is separated into two unique sections- Future World and World Showcase.
    is a prominent landmark which personifies ancient
    tradition and modern art. ,” officially leaving behind his pulp years until 2008′s “Indiana Jones and the Kingdom of the Crystal
    Skull. Exciting water rides including the 10-story
    high Water Bobsled offer thrills, and an amazing variety of different pools and leisure facilities make it easy to enjoy the day
    away. For the kids or the kids at heart, there are many arcades and
    go kart tracks for your entertainment. Some animals are neither
    a reptile nor a mammal such as Dimetrodon. There are some strategies
    that you can use to ensure that you get the best deals on cheap
    flights. It’s 1 of these couple of dinosaurs which are given
    the gift of flight. The Pearl Harbor and USS Missouri Tour covers
    three historic sites that shaped the outcome of World War II in one complete tour.

  5. I every time spent my half an hour to read this weblog’s articles or reviews everyday along with
    a cup of coffee.

  6. After looking into a few of the blog posts on your blog, I seriously like your technique of writing a blog.

    I book-marked it to my bookmark site list and will be checking back in the near future.
    Please check out my website as well and let me know your opinion.

  7. You have made some decent points there. I checked
    on the web for additional information about the issue and found most people will go along with your
    views on this site.

  8. I simply couldn’t go away your website because I really enjoyed the standard information an individual provide for your visitors?
    Is going to be back often in order to inspect new posts

  9. ( Some formats may require additional apps support.
    But to make money online with Facebook, you need
    to be very creative. Secondly, reviews and ratings are important because the more you
    are talked about (especially positively) the higher your rankings will
    soar on search engines.

  10. Marvelous, what a weblog it is! This webpage provides useful
    facts to us, keep it up.

  11. I constantly emailed this web site post page to all my
    friends, since if like to read it after that my links will

  12. Shorter Term Unsecured Financial Loans Easiest Way To Make Funds
    On-Line Vacation Decorating On A Dime

  13. Hmm it looks like your website ate my first comment
    (it was extremely long) so I guess I’ll just sum it up what I
    had written and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog blogger but I’m still
    new to the whole thing. Do you have any recommendations for novice blog writers?
    I’d definitely appreciate it.

  14. I blog often and I genuinely appreciate your information.
    This article has really peaked my interest. I will
    bookmark your blog and keep checking for new information about once
    per week. I subscribed to your RSS feed as well.

  15. I’ll right away clutch your rss feed as I can’t in finding your email subscription hyperlink or e-newsletter service.
    Do you have any? Kindly permit me understand so
    that I may just subscribe. Thanks.

  16. Eliminate Trans fats, MSG and bad fats from your diet.
    , livestock and poultry are fed large amounts of corn, which shifts their natural Omega-3 content to mostly Omega-6.
    Here’s some great foods that contain ‘healthy fats’ that you can incorporate into your diet.

  17. I have read so many posts regarding the blogger lovers however this post is really a fastidious article, keep it up.

  18. Still, if you have a graphic mind, this can be more useful than
    the more traditional list format. So everybody preserve expand
    way and download iPhone apps simply. These Web-Stores are turning the iPhone into the platform like mobile marketing.

  19. I know this if off topic but I’m looking into starting my own blog and was wondering what
    all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet smart so I’m not 100% positive. Any tips or advice would be greatly appreciated.
    Thank you

  20. Nostra figlia ha frequentato una scuola pubblica elementare che ha incoraggiato, ma non ha reso obbligatorio uniformi.

    L’elenco di ciò che costituiva usura uniforme mi sembrava di essere molto varia
    (io vengo anche da una divisa che indossa sfondo) fondo
    blu o kaki, polo blu, bianco o rosso o oxford camicie di tela, dolcevita e comprendeva anche una maglietta rossa con
    la scuola logo. Isabel Marant Shorts El Universal de un Buen Tipo Calzado, se lo furgone
    un creer Orgullosos y confiado. Adema, para poder tener
    Una operacin ms mucho perfecta en la arena acontecimientos Deportivo la misma
    p Empleado patadas sin duda son las Estensioni de las Regioni para Cada Uno localizar.
    Isabel Marant Spring 2014 Pertanto, consentendo loro di essere completamente impermeabile senza buchi creati da avvio.
    Stivali Timberland sono uno dei primi a fare
    questa affermazione.. Isabel Marant Wien Shop [24] Alcuni americani
    hanno cercato di organizzare un boicottaggio degli inserzionisti il ​​suo show in segno di
    protesta Lewinsky exploit sua fama. [25] Tuttavia, lo spettacolo ha debuttato a rating molto alti, [24]
    e il New York Times, ha detto che dopo anni di tentativi
    di incassare la sua fama disegnando borse e altri schemi selfmarketing, Ms.
    Isabel Marant Sneaker Online Quanto a me, devo indossare scarpe scomode per un po ‘, in attesa di un altro paio d’ore, ma il mio incidente o inconveniente, o la sera ho finito.

    Ho le mie dita, dei piedi, cavigliere e anelli punta cercando di
    essere più attraente per lo spettacolo. Dicker Boots
    Isabel Marant Molti di questi siti web raggiungibili mondo illusorio in giro impegno
    con Manti Te Jersey cercato di aiutare si prende
    una posizione importante gigantesco colonnato progettato abbastanza Antonio Gates Womens Jersey ben
    oltre i giochi che ti aiuteranno a dimostrare di essere un importante numero
    di giocatore di poker avidi. Gente promessa luminosità che frequentano la leggerezza
    progettate per l’affidabilità e anche le intenzioni d’arte.
    Isabel Marant Basley È una delle cose più preferite che faccio al mondo, ha detto il rabbino
    Guarda Stein, 77, in una recente intervista. Amare l’interazione con gli studenti e di essere in grado di
    aprire gli occhi per come l’ebraismo avvicina i fatti fondamentali della vita.
    Isabel Marant Neue Kollektion Nel mezzo di tutto questo Cantiere Bar
    and Grill, un comodo alto bar, ristorante e bar grezzo, dove ogni centimetro di spazio della parete è ricoperta con un valore di un museo di modelli di navi,
    immagini marine, yacht club guidone e vecchie insegne boatbuilders pubblicità.
    Osservazioni per la Chesapeake Bay giocare su uno schermo TV.

    Isabel Marant Wedges Sneaker

  21. Should you choose one of the models that computes the caloric intake,
    be sure to stay within the recommended daily allotment that the scale shows you.
    Remember, most people use the bathroom weight
    scale first thing in the morning, still groggy from sleep and without our glasses.
    I want you to gain weight smartly and the healthy way.

  22. When you log in to Windows, you can see that your HP Compaq
    NX7400 battery is detected by your laptop because it shows in the battery icon located in the
    system tray the remaining battery charge and the computer
    shows that it is charging. Next-generation Intel processors are always seen first
    in higher-end laptops, and true to form, the Asus
    G75VW-AS71 incorporates a quad-core third-gen Core i7 processor and upgraded Nvidia Ge
    - Force GTX 660M graphics, a big upgrade from the
    Asus G74SX-A2 CNET reviewed at the end of last year.
    The Asus 16″ Intel Core 320GB Laptop, Model: N61JQ-X2 features powerful internal technologies to support the multimedia driven computer user, as well as professional business users.

  23. Appreciating the dedication you put into your website
    and in depth information you provide. It’s good to come across a blog
    every once in a while that isn’t the same old rehashed material.
    Fantastic read! I’ve saved your site and I’m including your RSS feeds to
    my Google account.

  24. I like the helpful information you provide in your articles.
    I’ll bookmark your blog and check again here regularly.
    I am quite sure I will learn many new stuff right here!
    Good luck for the next!

  25. Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She
    placed the shell to her ear and screamed. There was a hermit crab
    inside and it pinched her ear. She never wants to go back!
    LoL I know this is totally off topic but I had to tell someone!

  26. Great website. Plenty of helpful info here. I am sending it to several buddies ans additionally sharing in delicious.

    And naturally, thank you for your effort!

  27. The Pre-Talayotic Period or Cave Era from 2000 – 1300BC, the Talayotic Period or Bronze age,
    1300 – 800BC and the Post Talayotic Period or Iron Age, 800 – 100BC.

    Another great tip on how to stop a panic attack
    on a plane is by being prepared. Maybe you won’t have
    to worry about a major event, a frightening event or miles
    and miles of snow and ice, but think about how important
    it is to be there for your partner everyday.

  28. Keep in mind that it really is one in four possibility of
    hitting a hand on pair additionally. In order to obtain new cards you ought to duel people and
    earn a few points, which you need to use to
    buy packs. I purchased the D-Link 6620G for your
    rich feature set this also article briefly summarizes the
    good, the not so good, as well as the ugly with this unit.

  29. Pretty section of content. I just stumbled upon your weblog and in
    accession capital to assert that I acquire actually enjoyed account your blog posts.
    Any way I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

  30. Yes! Finally someone writes about wood floor fitters West London.

  31. Hello there, You have done a fantastic job. I will certainly
    digg it and personally recommend to my friends. I’m confident they will be benefited from this website.

  32. Thanks for sharing your thoughts. I truly appreciate your efforts and I am waiting for your further post thanks once again.

  33. The other est way is to physically switch-off the router-this
    way you will save power, increase the life of your router and also
    have the best security to your network. Security researchers have discovered a vulnerability in
    i – OS apps, onee that could allow hackers to force the apps to
    send and receive data from the hackers’ own servers rather than
    the legitimate ones they were coded to connect to, BITS reported on Tuesday.
    This week’s gathering brought together computer hackers from
    around the world and it was show time. The MG has a single core processor and plenty of memory for the casual and even first person shooters
    I tried and no game or app had any problems.
    Smart TVs are turned iinto ‘slaves’ that be controlled by hackers who turn the set’s front
    facing camera into a spy cam on innocent viewers.

  34. That is very attention-grabbing, You’re an overly skilled
    blogger. I’ve joined your feed and look ahead to searching
    for more of your fantastic post. Also, I’ve shared your site in my social networks

  35. I’ll right away take hold of your rss as I can’t find your email subscription hyperlink or newsletter service.
    Do you’ve any? Please permit me understand so that I could subscribe.


  36. This article gives clear idea designed for the new viewers of blogging, that actually how to
    do blogging and site-building.

  37. Whats up this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to
    manually code with HTML. I’m starting a blog soon but have no coding knowledge so I
    wanted to get guidance from someone with experience. Any help would be enormously

  38. If you think that writing on Twitter, ‘I can not think my life is now it sucks.
    sensor 4 way G-sensor, Light sensor, Distance Sensor, Motion Sensor Keyboard Vibrant keyboard input.

    ” There is a pretty simple solution to this, but just how you go about opening Facebook in China will depend on how long you’re going to be here.

  39. Hi friends, pleasant article and good urging commented here, I am actually enjoying by these.

  40. Curs BNR Romania
    I don’t know whether it’s just me or if perhaps everybody else experiencing issues with your site.
    It appears as though some of the text in your content are running
    off the screen. Can someone else please provide feedback and let me know if this is happening to them too?
    This may be a problem with my internet browser because I’ve had this happen before.

  41. Hey there outstanding blog! Does running
    a blog similar to this take a great deal of work?
    I have very little expertise in coding however I was hoping to start my own blog soon.
    Anyhow, if you have any suggestions or tips for new blog owners please share.
    I know this is off subject however I simply needed to ask.
    Appreciate it!

  42. chanel South Africa
    Somebody essentially lend a hand to make seriously articles I would state.
    That is the first time I frequented your website page
    and so far? I surprised with the analysis you made to make this actual publish
    extraordinary. Magnificent job!


  1. The best way to get Free PSN Codes | uidjohnni

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 »