I have this select:
<select id="mySelect">
<option value="Test 1">Test 1</option>
<option value="Test 2">Test 2</option>
<option value="Test 3">Test 3</option>
<option value="Test 4">Test 4</option>
<option value="Test 5">Test 5</option>
<option value="Test 6">Test 6</option>
<option value="Test 7">Test 7</option>
<option value="Test 8">Test 8</option>
</select>
and I'd like to move the second option (Test 2) at the end of this select list. Can I with jQuery?
In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property.
Method 1: Append the option tag to the select box The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection.
The option to be removed is selected by getting the select box. The value to be removed is specified on the value selector (value='optionValue') on the select box. The remove() method is then used to remove this selected option.
var $select = $('#mySelect');
$select.find('option:eq(1)').appendTo($select);
Live DEMO
Placing the option in the fifth place:
var $select = $('#mySelect');
var desiredIndex = 5;
$select.find('option').eq(desiredIndex).before($select.find('option:eq(1)'));
Live DEMO
var sel = $('#mySelect');
sel.find('option:eq(1)').appendTo(sel); // insert to last position
Demo
sel.find('option:eq(1)').insertAfter('option:eq(5)'); // insert to a specified position
Demo2
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