Select lists in jQuery

Today I was working on a programming problem whereby I needed to populate a select element (rendered as a drop down list) with all the elements in a JSON object returned by an AJAX call to a PHP script. I saw this as a three step process:

  1. Delete all the existing option elements from the list.
  2. Add each entry in the JSON object (an array of addresses) as an option child element of the select list.
  3. Show the list (it is hidden by default).

I already knew how to show the list – $('#list_id').show() - but my knowledge of jQuery didn’t stretch as far as populating lists. Disappointing, both of the books I have recently purchased about jQuery (JavaScript & jQuery: The Missing Manual and jQuery: Novice to Ninja) did not cover this topic. As usual though, Google and StackOverflow came to the rescue with these two questions:

  1. Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
  2. jQuery: Best practice to populate drop down?

The accepted answer on both questions worked, and I now have the result I want.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.