DumpsterDoggy

Tutorials

Search
Newest Articles
Recent Tutorials
Related Blogs
Get Microsoft Silverlight
Twitter Updates

Bookmark This

Load Drop Down with jQuery

By: Chris Missal

Page 2

If you're slightly familiar with jQuery, you'll recognize the following lines of code. These lines get a reference to our "dd_state_list" select element and the jQuery object.

$("#dd_state_list")
$.getJSON()

Now we're going to use these references commbined in one function. We'll specify the file we're calling (for this example, I'm using a static html page, but it can be anything that returns response text back to the browser), any parameters and the function to execute when ready.

$.getJSON("javascript/visited_states.txt", { userid: "20001" }, function(data) {
    $.each(data.states, function(i, state) {
        $("<option>").attr("value", state.code).text(state.name).appendTo("#dd_state_list");
    });
});

Starting at the beginning of this code, you'll first notice the getJSON function. This one accepts a URL (for this example I'm calling a text file, but you probably wouldn't in a real project), an array of parameters, (in this case, I'm passing in the user ID of whom we're fetching the states list) and a function. I'm using an inline function, but you don't have to.

This callback function contains the jQuery .each fucntion which works as a loop. I'm looping through all of the elements in the "states" property (which happen to be unnamed arrays containing a code and name field). Inside the .each function I have written a long single line of code that performs 4 tasks.

  1. Create an <option> element.
  2. Set/create an attribute with a value contained in the "code" field.
  3. Set the inner text to the value found in the "name" field.
  4. Append this newly created element to the element with an id equal to "dd_state_list".

When the loop is done, all your elements are added to the DOM. It's that easy!