多个动态组合框javascript

时间:2012-11-22 11:04:36

标签: php javascript mysql combobox

有没有机会有一个组合框,每当我在那里选择一些东西时,它会打开一个新的组合,等等,直到没有更多的数据可供选择?

(不得重复选项)

Combo1 - (opt1-opt2-opt3) - 选择opt1
Combo2 - (opt2-opt3) - 选择opt3
Combo3 - (opt2)

组合框应该由查询使用php和mysql填充。

我该怎么办? 干杯!

1 个答案:

答案 0 :(得分:3)

这是一些jquery将执行此操作:

<强> HTML

<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>

<强>的Javascript

$('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);
        }
    }
});​

<强> Demo

<强>解释

// Adds an event listener to each combo box that is created dynmically
$('body').on('change', '.combo', function() {
    // Gets this selected value
    var selectedValue = $(this).val();

    // Checks if there are enough options left to create another combo box
    if (selectedValue !== '' && $(this).find('option').size() > 2) {
        // Clones the just selected combo box and get the current and next combo index
        var newComboBox = $(this).clone();
        var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
        var newComboBoxIndex = thisComboBoxIndex + 1;

        // Removes any "children" combo boxes
        $('.parentCombo' + thisComboBoxIndex).remove();

        // Checks if a blank value is not selected to create another combo box
        if (selectedValue !== '' && $(this).find('option').size() > 2) {
            // Gives this new combo box the correct id, index, parent class
            newComboBox.attr('data-index', newComboBoxIndex);
            newComboBox.attr('id', 'combo' + newComboBoxIndex);
            newComboBox.addClass('parentCombo' + thisComboBoxIndex);

            // Removes the selected option from the new combo box
            newComboBox.find('option[val="' + selectedValue + '"]').remove();

            // Adds the combo box to the page. Disco!
            $('body').append(newComboBox);
        }
    }
});