.val with an invalid value when choosing

I have a <select> , and when I click the mouse, the user can select the following option:

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

The problem is that in the last variant $opt.next().val() returns some non-selectable value, and apparently jQuery chooses the first option by default. I would like him to be the last.

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

+4
source share
2 answers

Here's a more efficient way to do this:

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

If you want to stick with jQuery, set option to:

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

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

+4
source

I would just go to business to be honest. It would be simple to add the following:

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

All Articles