逐个动态添加optgroup和选项

时间:2015-02-24 08:57:42

标签: javascript jquery html

我根据特定条件分组了多个复选框: enter image description here

我想填充一个分组下拉列表,如下所示:

enter image description here

分组下拉列表将从图像1中选中所有值(复选框已选中)。单击复选框后,我要将该复选框值添加到该特定组下的分组下拉列表中。

在我的情况下,如果用户选择了选项5,问题2中的选项6和问题3中的选项9,则我的分组下拉列表将具有如下值:

Question2
  -option 5
  -option 6
Qution3
  -option 9

这里是jsfiddle link

1 个答案:

答案 0 :(得分:1)

您可以尝试查看复选框change事件,并重复所有复选框以收集问题。然后,为选择生成HTML。

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>