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:
- Delete all the existing
option
elements from the list. - Add each entry in the JSON object (an array of addresses) as an
option
child element of theselect
list. - 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:
- Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
- jQuery: Best practice to populate drop down?
The accepted answer on both questions worked, and I now have the result I want.