2

so I'm trying to reverse the order of a select element with multiple values with the following code:

<select multiple="multiple">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
</select>

script:

    var a = [];
    $('option').each(function() {
    a.push($(this).val());
    });

    a.reverse();

    for (i = 0; i < a.length; i++) {
    $('option').index[i].text(a[i]);
    }

and apparently I can't get the index of my option element to set it's value to the reverse order.

krafterwerk
  • 21
  • 1
  • 3

4 Answers4

3

You can do it a slightly different way too if you're interested:

//  Grab the options
var $select = $('select');
var options = $select.find('option');

// turn the nodelist into an array and reverse it
options = [].slice.call(options).reverse();

// empty the select
$select.empty();

// add each option back
$.each(options, function (i, el) {
  $select.append($(el));
});

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
2

The index property is a function not an array. However, you are looking for .eq(i), or better, pass a function to .text:

$('option').text(function(i) {
    return a[i];
});

Alternative, you coukd change the order of the elements itself, see How may I sort a list alphabetically using jQuery?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

If you use .eq(1) as suggested by @FelixKing in the comments, that should do it:

$('option:eq(' + i + ')').text( a[i] );
PeterKA
  • 24,158
  • 5
  • 26
  • 48
1

It's better to reorder option tags itself I think, not just reordering the text ex: if one element is selected by default, or having some data attributes, you will mess up it, thus following solution would work the best:

$('.reversed option').each(function () {
      $(this).prependTo($(this).parent());
});

This way we iterate through the options and prepend each of them to the select tag, finally we get them in reversed order

More optimal (for performance) way:

var select = $('.reversed');

select.find('option').each(function(){
    $(this).prependTo(select);
});

http://jsfiddle.net/6pk4z72o/

George G
  • 7,443
  • 12
  • 45
  • 59