Search code examples
jqueryhtmlcssoptgroup

Show the selected option with group label in <optgroup>


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 ?


Solution

  • Add the values what ever you want to show. As below i have done.

    <select id='grp_option'>
      <optgroup label="Group 1">
        <option value='Group 1 - Option 1.1'>Option 1.1</option>
      </optgroup> 
      <optgroup label="Group 2">
        <option value='Group 2 - Option 2.1'>Option 2.1</option>
        <option value='Group 2 - Option 2.2'>Option 2.2</option>
      </optgroup>
    </select>
    

    Then just add this script. Here you go

    $('#grp_option option').each(function () {
         $(this).data('txt', $(this).text());
    });
    
    $('#grp_option').change(function () {
     $('option', this).each(function () {
        $(this).text($(this).data('txt'));
     });
    
     $(this).find('option:selected').text($(this).find('option:selected').attr('value'));
    });
    

    Its done.