How can I, using jQuery, set the \"next\" item of an already selected item as \"selected.\"
For example, if I have:
Update:
As of jQuery 1.6+ you should use prop() instead of attr()
in this case.
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);
Original Answer:
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.
$('#next').click( function(){
$('#colored_background option:selected').next('option').attr('selected', 'selected');
changeBackgroundColor();
});
Working at What is my favorite color?. Click on the arrows.
$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');
Check out working code here http://jsbin.com/ipewe/edit
This is what i just used, i like how clean it is :-)
$('select').val(function(){
var nextOption = $(this).children(':selected').next();
return $(nextOption).val();
}).change();
you can use
$('option:selected').next('option')
or
$('option:selected + option')
And set the value:
var nextVal = $('option:selected + option').val();
$('select').val(nextVal);