Reputation: 173
I want to access the value of the select option that one before the previous one of the selected one, meaning 2 away from the selected one. (sorry, it's hard to phrase it!)
For instance, if "4" is selected from here, I want to get the value of the option "2".
<option value ="1">1</option>
<option value ="2">2</option>
<option value ="3">3</option>
<option value ="4">4</option>
I know there is prev method for the immediately previous one, but how about the other ones?
Thanks!
Upvotes: 2
Views: 181
Reputation: 263167
As others have said, you can call prev() twice.
An alternative, more scalable solution is to use prevAll(). It returns elements ordered from the closest sibling outwards, so you can combine it with eq():
var siblingValue = $("option:selected").prevAll().eq(1).val();
This way, you won't have to chain multiple calls to prev()
if you want to move more than 2 options away from the selected one.
Upvotes: 2
Reputation: 83376
The prev function will get the preceding sibling for a given node; calling it twice will accomplish what you want.
var element = $("option[value='4']");
var prev2 = $(element).prev().prev();
alert(prev2.val());
//alerts 2
Here's the fiddle
Upvotes: 1
Reputation: 34863
You could do this
$("select").change(function(){
var a = $('select option:selected').prev().prev().text();
alert(a);
});
Example: http://jsfiddle.net/jasongennaro/NcPgV/
However, this returns nothing when the selection is 2 or lower.
Upvotes: 3