【问题标题】:Implement Exclusive Option in Multi-Select: clear other entries on selecting it, clear it on selecting others在多选中实现独占选项:选择它时清除其他条目,选择其他时清除它
【发布时间】:2022-02-03 23:25:10
【问题描述】:

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

  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
}

有什么建议吗?

【问题讨论】:

  • 在多选时 val() 返回一个数组。检查数组中的内容
  • 我不能。我需要知道刚刚单独选择了什么。我不能只说如果数组包含我的值,则强制它为我的值。如果是这种情况,我将永远不会退出独占选项条件。你明白我的意思吗?
  • 我知道您可以只拥有一个特定值,也可以拥有其他任何值的组合。这不正确吗?
  • 没错。但是,如果选择了一个特定的值,之后我将无法选择其他任何东西,我应该可以。这就是为什么我不能问“我的数组是否包含这个值”。你是说数组中item的order能告诉我最新添加的item吗?
  • 当然可以。可以拼接数组,设置select的更新值

标签: javascript html jquery


【解决方案1】:

这里有一个类似的线程,Mutual exclusion for <option>s in a <select>?。我们需要跟踪 current 选择数组并将其与 latest 选择数组进行比较。这将告诉我们刚刚选择了什么。

解决方案:

// 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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多