Reputation: 18427
I've been stuck on this for quite some time now, not being able to solve it myself. Say I have this select:
<select>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
</select>
and I have two buttons - next and prev. If someone clicks next then the next option is selected and vice versa. The problem I'm having is - how do I completely ignore the optgroups in this scenario? (i.e. if Chicago Bears
is selected, pressing previous should select Washington Redskins
).
here's a jsfiddle that illustrates the issue. I've tried many solutions but all of them got messy pretty fast. Any ideas?
Thanks in advance!
Upvotes: 0
Views: 277
Reputation: 104775
You can just check if the prev or next option
exists, if not, do some logic, if so, use it (here's a sample with previous)
$('#prev').on('click', function() {
var current = $('select option:selected'),
previous = current.prev("option");
if (previous.length)
$('select').val(previous.val());
else
$('select').val(current.closest("optgroup").prev("optgroup").find("option:last").val());
});
Upvotes: 2
Reputation: 133403
You can use .index(), it searches for a given element from among the matched elements.
$('#next').on('click', function () {
var selected = $('select option:selected');
var index = $('select option').index(selected);
var value = $('select option').eq(index + 1).val();
$('select').val(value);
});
$('#prev').on('click', function () {
var selected = $('select option:selected');
var index = $('select option').index(selected);
var value = $('select option').eq(index - 1).val();
$('select').val(value);
});
Upvotes: 1