Search code examples
jqueryoptgroup

jQuery manipulating select box while ignoring optgroups


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!


Solution

  • 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);
    });
    

    DEMO