代码之家  ›  专栏  ›  技术社区  ›  gene b.

在多选中实现独占选项:选择时清除其他条目,选择其他时清除

  •  0
  • gene b.  · 技术社区  · 4 年前

    我有一个多选,其中一个选项必须是独占的:

    1. 如果它被选中,则多选中的任何其他先前选择都将被取消选择
    2. 如果在选择另一个选项时选择了该选项,则取消选择该选项

    我试图检查刚刚选择的选项,但是 .val() 给了我整体选择。

    $('#educationLevel').on('change', function(e) {
        var selection = $(e.target).val();
        // This gives overall selection, not the just-selected one for my checks
    }
    

    有什么建议吗?

    0 回复  |  直到 4 年前
        1
  •  0
  •   gene b.    4 年前

    这里也有类似的线索, Mutual exclusion for <option>s in a <select>? 。我们需要跟踪 现在的 选择数组并用 最近的 选择数组。这将告诉我们 只是 已选择。

    解决方案:

    // Global Var:
    // To implement an exclusive option in a MultiSelect dropdown,
    // we need to keep track of the current selection (a global var here) 
    // and diff this array with the latest selection array in change() event.
    var currSel = $('#educationLevel').val();
    
    // Change Event Definition
    $('#educationLevel').on('change', function() {
        var newSel = $(this).val();
        // Get diff from currSel; a 1-element array expected.
        // Diff in arrays: see: https://stackoverflow.com/a/33034768/1005607
        var diff = newSel.filter(x => !currSel.includes(x));
        // If exclusive option just got selected, delete all others
        if (diff.length) {
            if (diff[0] === '405') { // '405' is my exclusive option
               // If exclusive option just got selected ("405"), deselect all others 
               // in modified selection array
               newSel = ['405'];
            } else {
               // If non-exclusive option just got selected, ensure that the exclusive option 
               // is not in the modified selection array
               newSel = newSel.filter(el => el !== '405');
            }
            // Set dropdown to the modified new selection array
            $('#educationLevel').val(newSel);
        }
        // Clone latest selection array into current selection array
        currSel = [...newSel];
    }