More jQuery Fun – Auto Populating a Select Box

Note: This post was updated 8/2/2011 to include jsfiddle code snippets and better/smarter code overall. Enjoy!

Problem: You want to dynamically populate a select box and you don’t know how.

Solution: Easy, I will show you.

First off, I lied there is no built in way in jQuery (why?, I don’t know) to automatically populate a select box. But it actually is very easy. There are plenty of methods to accomplish this but I like to do it this was because utilizes the Option object and it doesn’t require html string concatenation.

The basics

Example 1:

Here is the code for the onclick event of that button:

More Dynamic

In this example I will populate the 2nd select box based on the value of the first one.

Example 2:

This time when I change something in the first sel, it does the changing of the second select box.

What now?

There are many paths you can go down to make your select boxes dynamic, whether that is auto populating them, adding or removing single values, making them submit forms, submitting ajax calls to populate etc. etc. The key to making your life easier is to understand the way the select element is handled. Think of it as an array of element objects (which it is), at each index is an option and each option has text and a value.

Need help implementing a specific example? Just ask in a comment!

Tags: ,

Paul Giberson (Aknosis) is an über techie, web development freak, husband and father of 1 (with twins on the way!!). He plays with PHP / MySQL / JavaScript / jQuery and LAMP stacks often. Catch his tweets at @aknosis.

  • http://www.aknosis.com Aknosis

    To sidestep my $(selector)[0].length = 0 to empty the select you can also do $(selector).empty();

  • zkilz

    Hi!
    Nice website. Im trying to create a dynamically select form that adds options from different variables automatically every 3 second. This will constantly go in a loop.

    Is this something i can use to do that?
    Do you know if there is any way to save the options so it doesn’t go blank on reload of the page?

    Thank you any answer.

  • http://www.aknosis.com Aknosis

    Thanks.

    It wouldn’t be to difficult to do.

    1. Setup your function that adds the options
    2. Set the interval to call that function every 3 seconds

    There is no real way to save the options other than a cookie, you could also look into some sort of hash magic but that becomes difficult to work cross browser (see jquery history plugin).

    I also can’t seemt to find an easy way to serialize the options into text for storage in a cookie, so you probably would want to append to your cookie as you add each item. You will want to use common functions to turn your Objects in JSON and vice versca, (search for toJson).

    So you really want something like this:

    function updateOptions(){
       //This would be your dynamic call, probably ajax request
       var newOption = new Option('name', 'value');
       var s = $('#select')[0];
       var l = s.length;
       s[l] = newOption;
       //some predefined method to get the cookie
       //and convert it back into an object
       var cookie = eval('('+getCookie('optionSvr')+')');
      //add new option
       cookie.push(newOption);
       setCookie('optionSvr',toJSON(cookie));
    }
    //Run every 3 seconds
    setInterval('updateOptions()',3000);
    


    Example (minus the cookie stuff)