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

前端 未结 2 913
被撕碎了的回忆
被撕碎了的回忆 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: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()
    

提交回复
热议问题