开发者

Using jQuery to get a select box value with the selectedindex

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();


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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜