Transform optgroup/option

Transform an optgroup/option select into two dependent selects

by treehillstudio

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<div class="wrap">
  <label for="choose-product">Product:</label>
  <select class="form-control dependent" name="product" id="choose-product" data-rowlabel="Option:">
    <optgroup label="TM2 35 5/30">
      <option value="34">2,5m (€83.54)</option>
      <option value="36">10m (€98.96)</option>
    </optgroup>
    <optgroup label="TM2 35 9/16">
      <option value="35">2,5m (€74.54)</option>
      <option value="37">10m (€89.96)</option>
    </optgroup>
  </select>
</div>

CSS

.wrap {
  padding: 1em;
}

JavaScript

$('select.dependent').each(function(i, sel) {
      var original = $(this).clone(),
        dependent = $('<select>').attr({
          name: this.name,
          class: 'form-control',
          id: this.name + '_dependent'
        }).insertAfter(this);
      $('<label>').attr({
        for: this.name + '_dependent'
      }).text($(this).data('rowlabel')).insertAfter(this);
      this.name = this.name + '_group';
      $('optgroup', this).replaceWith(function() {
        return $('<option>').text(this.label)
      });
      $('option:first', this).prop('selected', true);
      $(this).on('change', function() {
        dependent.html(original.children('[label="' + $(this).val() + '"]').html())
      }).change();
    });