Add options to select box jquery

Add options to select box jquery

Posted: gaqafuce Date: 07.07.2017

My last jQuery post looked at how to count the number of options in a select and then clear all options from the select.

This post looks at how to add a new option to a select with jQuery. The following is an example showing an already populated select. Clicking the "Add option" button adds a new option to the end of the select and makes it the selected one.

Clicking "Replace options" replaces them with a new set of options and then selects the "Green" one. Note that the above example will not work if you are reading this in a feed reader.

In this case click through to view this post in a web browser. Adding a single option can be done by appending HTML to the select box.

What is the best way to add options to a select from an array with jQuery

The select in the above example has an id of "example" i. To avoid having to write and add options to select box jquery HTML and stick with a more Javascript add options to select box jquery the new option can be appended with jQuery by creating a new option object.

nocuwahojopyx.web.fc2.com

This next example does not work correctly in Internet Explorer ; patagonia stock market will add the new option but only the britt miller stock broker and not display any text. This method gets a handle to the options and adds a new option to the array of options.

This does work in Internet Explorer and is the more traditional Javascript way of adding options.

add options to select box jquery

Using the final method above this last example shows how to replace the existing set of options with a new set, which may have been retrieved from an AJAX call or similar. Lines 1 to 7 define the new options with an associative array and the one which will be selected. This is what might have been retrieved from an AJAX call.

javascript - Adding options to a