jQuery

jQuery Add Options To Select from Array

jQuery Add Options To Select from Array will help you add options dynamically to select dropdown from a pre-determined array. Read on to find out more about this simple solution.

Example to Add Options To Select from Array using jQuery

Let’s assume that you have already created an array called “dropdown_values” that you want to add to a select dropdown with ID “my_states”. This select dropdwon already consists of some values.

Complete jQuery Code:

//Declare your array first in key: value format
dropdown_values = {"1":"Dallas","2":"Texas","3":"Philly"};

//Then for each of the values of the array, append those values into the existing select "my_states" dropdown
$.each(dropdown_values, function(key, value) {
$('#my_states')
.append($('<option>', { value : key })
.text(value));
});

So here’s how you can add options to select dropdown from array using jQuery.

Simple, isn’t it?

Do you know of any other ways to use jQuery to Add Options To Select from Array? Feel free to share by commenting below.

One Comment on jQuery Add Options To Select from Array

  1. 1

    How to sort? the output options are sorted by option value, what if i need sort by option text? thanks for your code

Share your thoughts, comment below now!

*

*