In this tutorial, we will dynamically populate a select dropdown box using jQuery.

A sample usage of this is when we have a list of countries and we want display its corresponding cities in another select box.

Here is the live DEMO of Autopopulate Select Dropdown Box Using jQuery.

HTML head

Let us include our jquery file in our <head> area.

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

HTML body

We will be needing two dropdown select boxes. The first one(#selection) would contain the list of categories and the second(#selectionlist) would be the result list.

The #result paragraph would contain our notification message.

        <p>
            Select Dropdown
        </p>
        <p>
            <select id="selection">
                <option value="">
                    - Select Item Here -
                </option>
                <option value="food">
                    List of Food
                </option>
                <option value="animals">
                    List of Animals
                </option>
                <option value="flowers">
                    List of Flowers
                </option>
            </select>
        </p>
        <p>
            DropDown Result
        </p>
        <p>
            <select id="selectionresult"></select>
        </p>
        <p id="result">&nbsp;</p>

jQuery Script

On page load, we would hide our #selectionresult using the hide() jquery function.

Our AJAX request is triggered whenever we select a value in our dropdown box using the change() jquery function. When we send a request, we set our #result to “Retrieving …” to notify the user that we are already sending a request to our remote file.

Once we receive the response from our remote file, we will insert the response text msg in our #selection using html() jquery function. If the msg result is empty, we will simply display a notification message like “No item result”.

        <script type="text/javascript">
        $(document).ready(function(){
            $("#selectionresult").hide();

            $("#selection").change( function() {
                $("#selectionresult").hide();
                $("#result").html('Retrieving ...');
                $.ajax({
                    type: "POST",
                    data: "data=" + $(this).val(),
                    url: "demo/jquery-autopopulate-select-dropdown-box-response.php",
                    success: function(msg){
                        if (msg != ''){
                            $("#selectionresult").html(msg).show();
                            $("#result").html('');
                        }
                        else{
                            $("#result").html('<em>No item result</em>');
                        }
                    }
                });
            });
        });
        </script>

PHP

Here is the content of our remote file.

In $expectedValues we created an array list of our expected values, hence, if the posted value from our main page is not found in this array, we will return an empty message.

The $selectionArr contains the list of items for each data entry. We call the array index of our selected data. Once selected, using foreach, we will run a loop in the list of data under our selected array and echo each inside the <option> tag. In this way, our main page will be able to retrieve our data in HTML form and is ready to be inserted in our <select> tag.

    $expectedValues = array("food", "animals", "flowers");

    $selectionArr['food'] = array('pizza', 'spaghetti', 'rice');
    $selectionArr['animals'] = array('cat', 'dog', 'girrafe', 'pig', 'chicken');
    $selectionArr['flowers'] = array('rose', 'sampaguita');

    if (isset($_POST['data']) and in_array($_POST['data'], $expectedValues)){
        $selectedArr = $selectionArr[$_POST['data']];

        foreach($selectedArr as $optionValue){
            echo '<option>' . $optionValue . '</option>';
        }
    }
  • http://www.evucan.com Arjun

    Very clearly explained – many thanks :)

  • CodingCereal

    you’re welcome. thanks for reading :)

  • Rolly

    Very nice stuff.. I will try this on IE 8 and see if there is a bug.. Thanks

  • Rolly

    Great bug free on IE 8.. Thanks for your great tutorial..

  • http://netsky32.blogspot.com netsky32

    Thanks dude, this is what i want. Simple and easy to understand.

  • Geller

    Great, its working fine,i populate the data from database now the issue is, i can’t stay back the value after posted?, second dropdown is hide after postback.

    any solution plz?

    Thanks

  • webosb

    Jhoy, this is a great tutorial. Is it possible to make this default it’s value to something? or make it automatically click a drop down value on page load?

  • Larry Woods

    Great tutorial and it works find. But, never being satisfied, how about a 3 select example?

  • http://jhoyimperial.wordpress.com/ Jhoy Imperial

    thanks

    ok. ill try to make one when i get a time :)

    jhoy

  • Mathieu

    Thank you for this little tutorial, easy to understand even for a noob like me.

  • sunil yadav

    Thanks a lot …. its working as expected.

  • jose

    This works great, except for one thing. you created you element first the first time, and you can use the code above. But what if you are editing. you have to show the the 2nd select with all the values, but the correct element must be pre-selected. Can it be done with a slight modification to the script above? Basically there has to be a way to call the ajax not only onchange but onload, right

  • karl

    Hi,

    Why can’t i make the result appear?

  • Gosain

    Hi, I tried to implement this but got stuck at a strange problem. I tried to fill by pulling data from MySql. Everything works fine till “$result = mysql_query($sql);” but when I try to run while loop and no data is returned, A blank dropdown still shows instead of no item data. This happens even when I return no data and run only this while loop: “while ($row = mysql_fetch_assoc($result)){}”

    Pls help.

    Thanks.

  • devang

    Very nice.

  • OpenBSD

    Hi, This Worked Perfectly.
    How To add 1 level after result(3 dropdown)? Example :
    Flower =>rose=>1 …(etc)
    Flower =>sampaguita=>2 …(etc)
    if click flowers show rose, so if click rose show three result 1 (etc).
    my exmample nicly for country/state/city list.
    thanks for any reply.
    best regrads.

  • System Down

    hi,
    I have any problem. with this methos not send utf-8 character to mysql database. when send selectionresualt ( example : الامیر ) save ?????? in mysql. how to fix this ?

  • Adi

    Hi!

    Is it possible to add values to the second dropbox? Like Rose = 1 Sampaguita = 2 and pass those values through a form instead of the labels?

  • Adi

    I solved it. I am posting this simple solution here if anyone else needs it.

    This will send a numeric value instead of the label.

    $i = 0;

    if (isset($_POST['data']) and in_array($_POST['data'], $expectedValues)){
    $selectedArr = $selectionArr[$_POST['data']];

    foreach($selectedArr as $optionValue){

    echo ” . $optionValue . ”;
    $i++;
    }
    }

  • http://www.studiostacks.com Jerry

    Works beautifully! Thanks for sharing!

    Jerry

  • jay

    Great tutorial. Saved me a lot of hair pulling this page has.

  • Arly

    I can’t make this work. how should I name the remote php file?

  • Ned

    Working great with codeigniter. Saved my time, Thanks.

  • tom

    Thank god someone has put this simply!

  • raimis200

    how to create if i want that after submit, second select box will be marked with selected. Now, if i will click submit, second select box will be reseted.

  • KerryB

    Thanks for this code. Had to modify it to get it working, in particular;

    * Change the line:
    if (msg != ”)
    -> to be:
    if (msg != “”)
    =>and correct the same problem in the line that has the .html(“)

    * When I did a cut & paste the single quote characters you are using have to be changed to ordinary ones ie: ‘

  • JQuest

    I got it working with the exception that the second drop-down box shows values but they are not selectable. What am I doing wrong? I’ve compared your working source code with mine and I cannot see a difference.

  • Ohnmarsoe Ss

    how to dynamic dropdown with database.

Recent Tweets

Sponsored Links

Recent Comments

 

"Minimalist Cereal 2"
design and theme by Jhoy Imperial

Email us at support@codingcereal.com

Copyright 2010 - 2011 © www.codingcereal.com