Select next option with jQuery

Viewed 31694

I'm trying to create a button that can select next option.

So, i have a select (id=selectionChamp) with several options, an input next (id=fieldNext), and i try to do that :

$('#fieldNext').click(function() {
    $('#selectionChamp option:selected', 'select').removeAttr('selected')
          .next('option').attr('selected', 'selected');

    alert($('#selectionChamp option:selected').val());      
});

But I can not select the next option.. Thanks !

8 Answers

I would expect such button to loop thru options, and also to trigger change event. Here is possible solution for that:

$("#fieldNext").click(function() {
  if ($('#selectionChamp option:selected').next().length > 0) 
    $('#selectionChamp option:selected').next().attr('selected', 'selected').trigger('change');
  else $('#selectionChamp option').first().attr('selected', 'selected').trigger('change');
});

Here is jsFiddle: http://jsfiddle.net/acosonic/2cg9t17j/3/

The other solutions don't work in case there are optiongroup elements in addition to option elements. In that case, this seems to work:

var options = $("#selectionChamp option");
var i = options.index(options.filter(":selected"));
if (i >= 0 && i < options.length - 1) {
    options.eq(i+1).prop("selected", true);
}

(You may think that the expression for i could also be written as options.index(":selected"), but that doesn't always work. I don't know why, an explanation would be welcome.)

Related