3

Is it possible with jQuery to get the value of a select box item based on the selected index? I ask because what I actually need is the value of the items before and after the current selectedindex for next/previous buttons. This is the code I tried but it did not work.

var my_value = $('#my_element_id').attr("selectedIndex").val();
Cloudkiller
  • 1,616
  • 3
  • 18
  • 26
  • possible duplicate of [To get selected value of a dropdown ( – Felix Kling Jun 29 '11 at 14:00

1 Answers1

4

This should do it (after my 3rd edit :-) )

It's quite verbose, but pretty easy to see what it's doing. I'm sure you can shorten it:

Here is a working example: http://jsfiddle.net/59SPw/

html:

<select id="my_element_id">
    <option>Alex</option>    
    <option selected="selected">IS</option>
    <option>Cool</option>
</select>

Js:

var selectedIndex = $('#my_element_id :selected').index();

if(selectedIndex  > -1)
{
    selectedIndex = selectedIndex + 1; //index() is 0 based, nth-child is 1 based

    var prevIndex = selectedIndex - 1;
    var nextIndex = selectedIndex + 1;

    var prev = $('#my_element_id :nth-child(' + prevIndex  + ')').val();

    var next= $('#my_element_id :nth-child('+  nextIndex + ')').val();

    alert(prev || "no previous");
    alert(next || "no next");
}
Alex KeySmith
  • 16,657
  • 11
  • 74
  • 152