Get the optgroup label and option value and show it in a div with Jquery


I have the following code:

    <optgroup label="fruta">      
        <option value="banana">banana</option>
        <option value="uva">uva</option>

    <optgroup label="legume">
        <option value="batata">batata</option>
        <option value="cenoura">cenoura</option>
<div id="label_value"></div>

I would like in JQuery to get the value of the label and value and play it in a div.


You can do it like this:

$('select').change(function () {
    var label = $(this).find(':selected').closest('optgroup').attr('label');


The code will fetch the selected option and then go up in the DOM to fetch that option optgroup . Then it reads the label attribute.

Scroll to Top