jQuery: find the for a selected value in a <select> element

前端 未结 2 900
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 09:48

I have a dropdown menu with different option groups. If someone selects an option, how can I check which optgroup it belongs to? For example if \'ferrari\' were selected, how wo

相关标签:
2条回答
  • 2021-02-20 10:49

    Well, in pure js:

    this.options[this.selectedIndex].parentNode.label
    

    Not a single function call and less code to boot. :-)

    0 讨论(0)
  • 2021-02-20 10:52

    You can do this using jQuery:

    $('select').change(function() {
        var selected = $(':selected', this);
        alert(selected.closest('optgroup').attr('label'));
    });​
    

    See a live example here: http://jsfiddle.net/jkeyes/zjLCp/1/

    Update: Yes you could use parent http://jsfiddle.net/jkeyes/zjLCp/2/

    selected.parent()
    
    0 讨论(0)
提交回复
热议问题