Over a million developers have joined DZone.

jQuery: Dynamically updating a drop down list

DZone's Guide to

jQuery: Dynamically updating a drop down list

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

We recently had a requirement to dynamically update a drop down list based on how the user had filled in other parts of the page.

Our initial approach was to populate the drop down with all potential options on page load and then add CSS selectors to the options that we wanted to hide. That worked fine in Chrome and Firefox but Internet Explorer seems to ignore CSS selectors inside a drop down list so none of the options were being hidden.

We therefore had to try and dynamically add and remove options from the drop down list instead.

The list that we initially loaded onto the page was like this:

<select id="foo" name="foo">
<option value="A" selected="selected">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="Not applicable">Not applicable</option>

Christian eventually came up with the following solution to hide/show those options and select the appropriate one after several hours of trial and error:

// captured on page load
var originalFooOptions = $("#foo > option");
var foo = $("#foo");
var dependentField = $("#fieldFooIsDependentOn");

if(notApplicable()) {
foo.children("option[value!='Not applicable']").remove();
foo.val("Not applicable");
} else {
$(originalFooOptions).each(function() {
var newOption = $(this).clone();
if ($(this).val() === dependentField.val()) {
newOption.attr("selected", "selected");

Another approach we tried was to try and dynamically update 'foo' rather than removing all the items and then adding them back.

Unfortunately we kept getting an 'unspecified error' on Internet Explorer 6 when we tried to set the selected value with that approach.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}