Search code examples
javascriptjqueryselecttoggleoptgroup

Toggle optgroup element in jquery


Is there any way to toggle an <optgroup> with jQuery or JavaScript?

I tried to change an <optgroup> with a normal <option> tag with attribute "disabled" and attach an onclick event, but it creates confusion when I click on closed select box on first time.


Solution

  • Yes, of course. We just need to get all the <option>, append these to the <select> and then remove all <optgroup.


    HTML

    <select id="myselect">
      <optgroup label="Swedish Cars">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
      </optgroup>
      <optgroup label="German Cars">
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </optgroup>
    </select>
    

    JQUERY

    var select = $('#myselect');
    select.find('option').each(function(){
      select.append( this.outerHTML );
    })
    
    select.find('optgroup').remove();
    

    JSFIDDLE

    https://jsfiddle.net/ehf1oh8w/