Homer_J
Homer_J

Reputation: 3323

jQuery populating dropdown using array, multiple arrays

Hi I'm populating a single select dropdown and using an array to populate the dropdown as follows:

var myOptions = {
    val1 : 'Albuquerque Aero (NM75)',
    val2 : 'Albuquerque FM&T (NM14)',
    val3 : 'Allentown (PA19)'
};

At the moment the dropdown 'value' and 'text' uses the same information pulled from the above array as follows:

$('<option></option>').val(text).html(text)

I need to have a different piece of information shown in the 'text' element so I wanted to use a multi-array as opposed to two separate arrays (more efficient?) but I'm struggling to get my head around multi-arrays in Javascript/ jQuery.

Is it as simple as:

var myOptions = {
        val1 : 'Albuquerque Aero (NM75)','Different text',
        val2 : 'Albuquerque FM&T (NM14)','Different text',
        val3 : 'Allentown (PA19)','Different text'
    };

How could I achieve what I am looking for? Is it even possible?

Upvotes: 0

Views: 935

Answers (2)

Muhammed Shevil KP
Muhammed Shevil KP

Reputation: 1396

Instead of arrays, better you use JSON. Try changing your source of values to a json object and loop through the object to fill select list

var myOptions = [
    {"val" : "Albuquerque Aero (NM75)", "text": "something"},
    {"val" : "Albuquerque FM&T (NM14)", "text": "something"},
    {"val" : "Allentown (PA19)", "text": "something"}
];

$(myOptions).each(function(i, e){
    $("#mySelect").append($("<option>").val(e.val).text(e.text));
});

check Fiddle

Upvotes: 1

Satpal
Satpal

Reputation: 133403

I would recommend you to modify the structure of your object (as of now its not valid).

You can create an array of objects with value and text which can be iterated and option can be created.

var myOptions = [{
  val: 'Albuquerque Aero (NM75)',
  text: 'Different text (NM75)'
}, {
  val: 'Albuquerque FM&T (NM14)',
  text: 'Different text (NM14)'
}, {
  val: 'Allentown (PA19)',
  text: 'Different text (PA19)'
}];

$.each(myOptions, function(index, item) {
  $('<option />', {
    html: item.text,
    value: item.val
  }).appendTo('select');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>

Upvotes: 2

Related Questions