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);
});
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())
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With