Explosion Pills
Explosion Pills

Reputation: 191749

.val with invalid value on select

I have a <select>, and on button click users can select the next option:

$(".someButton").on('click', function () {
   var $opt = $("select :selected");

   $("select").val($opt.next().val());
});

The problem is that on the last option, $opt.next().val() returns some unselectable value, and apparently jQuery selects the first option by default. What I would like is for it to stay on the last option.

Is there any way to do this (preferably without checking the position of $opt or the length of $opt.next())?

Upvotes: 4

Views: 688

Answers (2)

CodePB
CodePB

Reputation: 1756

I would just handle the case to be honest. It would be simple to add the following:

if(!$opt.is(':last-child')) {
    $("select").val($opt.next().val());
}

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219938

Here's a more efficient way to do it:

$(".someButton").on('click', function () {
   var el = $("select")[0];
   el.selectedIndex = Math.min(el.selectedIndex + 1, el.length - 1);
});

If you want to stick to jQuery, set the option to selected:

$opt.next().prop('selected', true);

If $opt is the last one, .next() will return an empty set, so nothing will change.

Upvotes: 4

Related Questions