如何使用jQuery动态添加组合框

时间:2012-12-26 17:42:26

标签: javascript jquery combobox

我有这个正在创建一个组合框的工作代码:

您可以在此处看到它: jsfiddle

$('body').on('change', '.combo', function() {
    var selectedValue = $(this).val();

    if ($(this).find('option').size() > 2) {
        var newComboBox = $(this).clone();
        var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
        var newComboBoxIndex = thisComboBoxIndex + 1;

        $('.parentCombo' + thisComboBoxIndex).remove();

        if (selectedValue !== '') {
            newComboBox.attr('data-index', newComboBoxIndex);
            newComboBox.attr('id', 'combo' + newComboBoxIndex);
            newComboBox.addClass('parentCombo' + thisComboBoxIndex);
            newComboBox.find('option[val="' + selectedValue + '"]').remove();
            $('body').append(newComboBox);
        }
    }
});

这导致了这种情况,每次我填充一个组合框,下一个打开。

one combobox only

如何更改代码才能拥有此功能?这意味着两个组合框打开(请忘记样式

Which means two comboboxes effect

谢谢。

2 个答案:

答案 0 :(得分:1)

如果您只想将组合框的数量加倍,可以使用for循环并根据计数器变量的值设置它们的值。

答案 1 :(得分:1)

我不完全确定您是否有意图,但似乎您希望拥有两个select元素的组,然后在用户选择值时添加新组。

在这种情况下,我建议将select中的两个fieldset分组为:

<fieldset>
  <select id="combo1" class="combo" data-index="1">
    <option></option>
    <option val="Opt1">Opt1</option>
    <option val="Opt2">Opt2</option>
    <option val="Opt3">Opt3</option>
  </select>
  <select id="combo2" class="combo" data-index="2">
    <option></option>
    <option val="Opt1">Opt1</option>
    <option val="Opt2">Opt2</option>
    <option val="Opt3">Opt3</option>
  </select>
</fieldset>

然后查找那个父fieldset并像这样克隆它:

$('body').on('change', '.combo', function() {
  var selectedValue = $(this).val();

  var fieldset = $(this).parents('fieldset');

  if ($(this).find('option').size() > 2) {
    var newFieldset = fieldset.clone();
    var newComboBox = $(fieldset).children('.combo:first');
    var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
    var newComboBoxIndex = thisComboBoxIndex + 1;

    $('.parentCombo' + thisComboBoxIndex).remove();

    if (selectedValue !== '') {
        newComboBox.attr('data-index', newComboBoxIndex);
        newComboBox.attr('id', 'combo' + newComboBoxIndex);
        newComboBox.addClass('parentCombo' + thisComboBoxIndex);
        newComboBox.find('option[val="' + selectedValue + '"]').remove();
        $('body').append(newFieldset);
    }
  }     
});​

有一些细节可能并不完全符合您的需要,但总的来说这是我推荐的方法。

在此处找到更新的小提琴:http://jsfiddle.net/JaVVe/8/