Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I move an option at the end of the select list?

Tags:

html

jquery

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?

like image 796
markzzz Avatar asked Mar 15 '13 08:03

markzzz


People also ask

How do I change the Select option value?

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.

How do I add options to select box?

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.

How do I remove selected option from select?

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.


2 Answers

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

like image 73
gdoron is supporting Monica Avatar answered Nov 15 '22 01:11

gdoron is supporting Monica


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

like image 34
Anujith Avatar answered Nov 15 '22 01:11

Anujith