views:

3040

answers:

3

Hello,

How can I, using jQuery, set the "next" item of an already selected item as "selected."

For example, if I have:

<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>

We can see that "Number 2" is selected, and using jQuery, I'd like to set "Number 3" as selected, and remove the selected "attribute" from "Number 2". I'm assuming I need to use the next selector, but I'm not quite sure how to implement.

Any ideas? Thanks!

+6  A: 
$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');

Check out working code here http://jsbin.com/ipewe/edit

Dhana
A: 

you can use

$('option:selected').next('option')

or

$('option:selected + option')

And set the value:

var nextVal = $('option:selected + option').val();
$('select').val(nextVal);
Kobi
+2  A: 

If you want to select by the value of the option, REGARDLESS of its position (this example assumes you have an ID for your select):

var theValue = "whatever";
$("#selectID").val( theValue ).attr('selected',true);

You do not need to "unselect". That happens automatically when you select another.

GtotheB
Your answer is a more rounded answer. Which almost a year later has helped. Thanks.
Kris.Mitchell