Show the selected option with group label in <optgroup>

UI Dev picture UI Dev · Jan 20, 2015 · Viewed 8.5k times · Source

I have the following code. I want when an option is selected then with selected option the group label should be shown how to achieve it ?

<select id='#grp_option'>
 <optgroup label="Group 1">
 <option>Option 1.1</option>
</optgroup> 
<optgroup label="Group 2">
 <option>Option 2.1</option>
 <option>Option 2.2</option>
</optgroup>
<optgroup label="Group 3" disabled>
 <option>Option 3.1</option>
 <option>Option 3.2</option>
 <option>Option 3.3</option>
</optgroup>
</select>

I tried in jquery & googled out but no solution i found. I tried script like onchange

function showLabel(e){ 
 var selected = $('#grp_option :selected');
 var id = #grp_option;
 var cu_label = $(selected).val();
 var label=$(selected).parent().attr('label') + ' - ';
 var tlabel = label + cu_label; 
 //$(id).text(tlabel);
 console.log(tlabel);
}

In console.log i get Group 2 - Option 2.1. But i want to show this in select input value Any body knows how to achieve it ?

Answer

Nate Barbettini picture Nate Barbettini · Jan 20, 2015

You were close! Try this:

HTML

<label id="target" for="grp_option">Selected: </label>
<br/>
<select id="grp_option">
    <optgroup label="Group 1">
        <option>Option 1.1</option>
    </optgroup>
    <optgroup label="Group 2">
        <option>Option 2.1</option>
        <option>Option 2.2</option>
    </optgroup>
    <optgroup label="Group 3" disabled>
        <option>Option 3.1</option>
        <option>Option 3.2</option>
        <option>Option 3.3</option>
    </optgroup>
</select>

JS

$(document).ready(function () {
    $('#grp_option').on('change', function () {
        showLabel();
    });

    // fire on page load
    $('#grp_option').change();
});

function showLabel() {
    var selected = $('#grp_option :selected');
    var item = selected.text();
    var group = selected.parent().attr('label');
    $('#target').text('Selected: ' + group + ' - ' + item);
}

Here's a working fiddle: http://jsfiddle.net/ojj0L7ht/