0

I have this code in my script:

    var myobject = {
    'Any' : 'Any',
    '1' : 'One',
    '2' : 'Two',
    '3' : 'Three',
    '4' : 'Four',
    '5' : 'Five'
};

var select = document.getElementById("TypeList1");
for(index in myobject) {
    select.options[select.options.length] = new Option(myobject[index], index);
}

I am getting dropdown like this:

<select id="TypeList1" class="custom1 interactive1">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
  <option value="Any">Any</option>
</select>

But I want to generate like this way:

<select id="TypeList1" class="custom1 interactive1">
  <option value="Any">Any</option>  
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
</select>

Any ideas or suggestions? Thanks.

Rajnikanth
  • 2,745
  • 6
  • 31
  • 46

3 Answers3

4

You're relying on an associative (i.e. non-indexed) structure (object) to output according to index. Your index variable actually holds the named key of the property, not its index.

Instead, use an array, which IS indexed. Each entry in the array is a sub-array containing the value and the text for the option.

var arr = [
    ['Any', 'Any'],
    ['1', 'One'],
    ['2', 'Two'],
    ['3', 'Three'],
    ['4', 'Four'],
    ['5', 'Five']
];

var select = document.getElementById("TypeList1");
for (var i=0, len = arr.length; i<len; i++)
    select.options[select.options.length] = new Option(arr[i][1], arr[i][0]);
Mitya
  • 33,629
  • 9
  • 60
  • 107
2

You could simply add this line just after the for loop :

jQuery('option:last').insertBefore('option:first');
0

using jQuery You can do this as below.

Change your object as below,

var myobject = {
    '1' : 'One',
    '2' : 'Two',
    '3' : 'Three',
    '4' : 'Four',
    '5' : 'Five'
};
$("<option></option>", 
     {value: "Any", text: "Any"})
    .appendTo('#TypeList1');

$.each(myobject , function(i , v){
  $("<option></option>", 
     {value: i, text: v})
    .appendTo('#TypeList1');
});

Live Demo

Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90