DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

Set an option to be displayed at first position using jQuery

I have a select element with some options:

<select id="choose">
    <option id="first" value='null'>choose</option>
    <option id="g1" value='1'>gate1</option>
    <option id="g2" value='2'>gate2</option>
</select> 

The user selects an option and submits the form. The data is stored. Anytime the user comes back I want the previously saved option to be display at the top of the select element, instead of choose.

I do it e.g. this way

$("#choose").val("2");

It just highlights the option in the list, but choose is still the first element. How do I accomplish that?

Upvotes: 2

Views: 6555

Answers (4)

PetersenDidIt
PetersenDidIt

Reputation: 25620

Sounds like you want to move the selected item to the top after they select it.

Just bind to the change event and the find the selected option and prepend it to the #choose

var choose = $("#choose").bind('change',function(){
    choose.find('option:selected').prependTo(choose);
});

http://jsfiddle.net/petersendidit/ZuhqS/1/

Upvotes: 4

John K.
John K.

Reputation: 5474

See: http://jsbin.com/ipewe/edit Here's a sample...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
</style>
</head>
<body>
  <p>Hello from JS Bin</p>
  <p id="hello"></p>
  <select>
<option value="1" >Number 1</option>
<option value="2" selected="selected">Number 2</option>
<option value="3" >Number 3</option>
<option value="4" >Number 4</option>
</select>
<script type="text/javascript">
$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');
</script>

</body>
</html>

Upvotes: 0

rcravens
rcravens

Reputation: 8390

var prevSelVal = 2;
if(prevSelVal!=0){
    var elem = $('#g' + prevSelVal).remove();
    $('#first').remove();
    $('#choose').prepend(elem);
}

The code above removes the element from the list and places it at the top. It also removes your 'choose' element.

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237865

prepend should do the trick:

var choose = $('#choose');
choose.val(2).prepend(choose.find('[value="2"]'));

Upvotes: -1

Related Questions