Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding optgroups dynamically using jQuery

Tags:

jquery

list

<select id="myElement" multiple="multiple">
  <option value="1">Category Type</option>
  <option value="158">itemOne</option>
  <option value="157">itemTwo</option>
  <option value="7">My Type</option>
  <option value="20">itemThree</option>
  <option value="21">itemFour</option>
  <option value="22">itemFive</option>
  <option value="8">Category Yet Another</option>
  <option value="31">itemCheese</option>
  <option value="32">itemBrain</option>
</select>

I need to dynamically convert this so that "Category" options (anything that doesn't start with "item") is an optgroup, wrapping whaterver comes after it until the next Category option, so the above would end up looking like:

<select id="myElement" multiple="multiple">
  <optGroup label="Category Type">
    <option value="158">One</option>
    <option value="157">Two</option>
  </optGroup>
  <optGroup label="My Type">
    <option value="20">Three</option>
    <option value="21">Four</option>
    <option value="22">Five</option>
  </optGroup>
  <optGroup label="Category Yet Another">
    <option value="31">Cheese</option>
    <option value="32">Brain</option>
  </optGroup>
</select>

How can I iterate over this and change values to acheive the desired effect using jQuery?

like image 346
key2starz Avatar asked Sep 24 '12 08:09

key2starz


2 Answers

$.each(data, function () {

    if (prevGroupName.indexOf(this.Group.Name) == -1) {
        $prevGroup = $('<optgroup />').prop('label', this.Group.Name).appendTo('#ConfigurationId');
    } else {
        $prevGroup = $("optgroup[label='" + this.Group.Name + "']");
    }
    $("<option />").val(this.Value).text(this.Text).appendTo($prevGroup);
    prevGroupName.push(this.Group.Name);
});
like image 149
Parth Desai Avatar answered Oct 17 '22 05:10

Parth Desai


You have to iterate over the option elements and group them based on their contents. Using jQuery makes it way easier than just pure DOM API:

http://jsfiddle.net/kpykoahe/2/

$(document).ready(() => {
    const $cont = $('select');
    $('option').each((idx, el) => {
        const $el = $(el);
        if ($el.text().startsWith('item')) {
            $cont.find('optgroup').last().append($el);
            $el.text($el.text().substr(4));
        } else {
            $('<optgroup/>').attr('label', $el.text()).appendTo($cont);
            $el.remove();
        }
    });
});
like image 44
Michał Miszczyszyn Avatar answered Oct 17 '22 03:10

Michał Miszczyszyn