How to get the Index of select->option tag

后端 未结 8 1263
独厮守ぢ
独厮守ぢ 2020-12-09 10:35

                        
    
提交评论

  • 2020-12-09 10:46

    Use the standard index function of jquery like in this code example

    $("#sel option:selected").index()

    0 讨论(0)
  • 2020-12-09 10:47

    You can get the index of the element in this case by checking how many sibling elements the selected element has before it:

    $('#sel option:selected').prevAll().length;
    
    0 讨论(0)
  • 2020-12-09 10:58

    Only Bob's second answer is correct:

    $("#sel")[0].selectedIndex
    

    Works: http://jsfiddle.net/b9chris/wxeVN/1/

    Using .attr() works only if the user (or browser's DOM restore) has not changed the option selected since the page loaded: http://jsfiddle.net/b9chris/wxeVN/

    You could implement this as a jQuery extension, and get a little more info in the process:

    (function($) {
        $.fn.selectedOption = function() {
            var sel = this[0];
            return sel.options[sel.selectedIndex];
        };
    })(jQuery)
    
    $('button').click(function() {
        $('#output').text('selected index: ' + $('select').selectedOption().index);
    });
    

    http://jsfiddle.net/b9chris/wxeVN/102/

    What's returned by .selectedOption() is the actual option tag, so you can access .index, .value, and .text - a bit more convenient than just the index in typical usage.

    0 讨论(0)
  • 2020-12-09 11:03
    $("#sel").attr("selectedIndex")
    

    or

    $("#sel")[0] //to get the DOM element
    $("#sel")[0].selectedIndex
    
    0 讨论(0)
  • 2020-12-09 11:04

    You can actually do it without jQuery: var sel = document.getElementById( 'sel' ); var index = sel.selectedIndex;

    0 讨论(0)
  • 提交回复
    热议问题