Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jQuery to move an <option> to be the second element?

Tags:

jquery

How can I use jQuery to move a specific <option> to be the second option?

<select class="comestibles">
 <option>apple</option>
 <option>banana</option>
 <option>cantaloupe</option>
 <option>date</option>
 <option>eggplant</option>
 <option>fig</option>
</select>

<select class="comestibles">
 <option>apple</option>
 <option>banana</option>
 <option>cantaloupe</option>
 <option>date</option>
 <option>eggplant</option>
 <option>fig</option>
</select>

This code will make eggplant the first option... close but no cigar.

jQuery('select.comestibles').each(function(){
  $('option[value=eggplant]',this).prependTo(this);
}); 
like image 222
cwd Avatar asked Jan 23 '26 23:01

cwd


1 Answers

Assuming there's only one select element...

jQuery('option[value=eggplant]').insertAfter('option:first-child')

I also assume that you actually have value attributes on your elements.

http://jsfiddle.net/wNmLF/


The code in the question changed. Now it would be...

jQuery('select.comestibles option[value=eggplant]').insertAfter('select.comestibles option:first-child')

For the most recent change...

jQuery('select.comestibles').each(function(){
    var opts = $(this).children();
    opts.filter('[value=eggplant]').insertAfter(opts.first())
}); 
like image 192
2 revsuser1106925 Avatar answered Jan 26 '26 18:01

2 revsuser1106925



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!