Arti
Arti

Reputation: 3071

Add optgroup and options dynamically one by one

I have multiple check-boxes grouped based on certain condition: enter image description here

I want to populate a grouped dropdown like example given below:

enter image description here

Grouped dropdown will have all the values selected(checkboxes checked) from image 1. On click of the checkbox I want to add that checkboxes value to the grouped dropdown under that perticular group.

In my case if user selected option 5, option 6 from question2 and option 9 from question 3 then my grouped dropdown will have values like below

Question2
  -option 5
  -option 6
Qution3
  -option 9

here is jsfiddle link

Upvotes: 0

Views: 2000

Answers (1)

matewka
matewka

Reputation: 10148

You can try to watch checkbox change event and reiterate over all checkboxes to collect questions. Then, generate HTML for the select.

var questions = {},
  form = $('#questionsForm'),
  checkboxes = $('.a', form),
  select = $('#dynamic');

$(document).on('change', '.a', function() {
  var i, j, item,
    data = '';

  questions = {};

  checkboxes.each(function(idx, elem) {
    item = $(elem);

    if (!item.is(':checked')) {
      return true;
    }

    if (!questions[item.data('question')]) {
      questions[item.data('question')] = [];
    }

    questions[item.data('question')].push(item.data('option'));
  });

  for (i in questions) {
    if (questions.hasOwnProperty(i)) {
      data += '<optgroup label="Question ' + i + '">';

      for (j = 0, n = questions[i].length; j < n; j++) {
        data += '<option value="' + questions[i][j] + '">' + questions[i][j] + '</option>';
      }

      data += '</optgroup>';
    }
  }

  select.html(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="questionsForm">
  <input type="checkbox" class="a" data-question="1" data-option="1" id="1" />
  <label for="1">Question1-Option1</label>
  <br/>
  <input type="checkbox" class="a" data-question="1" data-option="2" id="2" />
  <label for="2">Question1-Option2</label>
  <br/>
  <input type="checkbox" class="a" data-question="2" data-option="3" id="3" />
  <label for="3">Question2-Option3</label>
  <br/>
  <input type="checkbox" class="a" data-question="5" data-option="1" id="4" />
  <label for="4">Question5-Option1</label>
</form>

<br/>
<br/>
<select id="dynamic"></select>

Upvotes: 1

Related Questions