对两个下拉列表交替约束的最佳方法

Best way to alternate constraints on two dropdowns

本文关键字:约束 最佳 方法 下拉列表 两个      更新时间:2023-09-26

我有两个具有相同值的下拉选择。我正在构建一个从源(左)单元到目标(右)单元的转换器.与类似单位相互转换是没有意义的。我知道如何在下拉选择中添加事件以从备用框中删除所选选项,但我不清楚如何编写此内容以产生最佳的 UI 体验。给出以下修剪后的情况:

<select name="srcUnit" id="srcUnit">
    <option value="Unit 1">Unit 1</option>
    <option value="Unit 2">Unit 2</option>
    <option value="Unit 3">Unit 3</option>
</select>
<select name="dstUnit" id="dstUnit">
    <option value="Unit 1">Unit 1</option>
    <option value="Unit 2">Unit 2</option>
    <option value="Unit 3">Unit 3</option>
</select>

解决这个问题的最佳实践是什么?如果您选择"单元 2"的来源,目标应该如何反应,将其删除?然后我需要一个重置按钮,或者如果您也在目的地选择"单元 2",请将源弹到其他东西(这似乎更糟和直观)?

忘记这个,只是在提交时验证?

检查每个下拉更改事件的新值。

如果还在另一个下拉列表中选择了该值,请将另一个下拉列表的值移动到下一个(或默认)选项。

若要向用户提供不应两次选择相同值的线索,请将已在另一个下拉列表中选择的值灰显。

我已经为您编写了代码,这是一个可执行片段:

$("#srcUnit, #dstUnit").change(function(){
    /*Detect wether we have srcUnit or dstUnit */
    if($(this).attr("id") == "srcUnit"){var otherUnit = "dstUnit";}
    else{var otherUnit = "srcUnit";}
    /*Save new Value*/
    var newVal = $(this).children("option:selected" ).val();
    /*Select next option in other dropdown if it's old value was selected*/
    if(newVal == $("#"+otherUnit+" option:selected").val()){  
       $('#'+otherUnit+' option:selected').removeAttr('selected').next().attr('selected', 'selected');
    }
    /*Update UI*/
    $('#'+otherUnit+' option').removeClass("disabled");
    $('#'+otherUnit+' option[value="'+newVal+'"]').addClass("disabled");
});
.disabled {
  color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="srcUnit" id="srcUnit">
    <option value="Unit 1" selected>Unit 1</option>
    <option value="Unit 2">Unit 2</option>
    <option value="Unit 3">Unit 3</option>
</select>
<select name="dstUnit" id="dstUnit">
    <option value="Unit 1" class="disabled">Unit 1</option>
    <option value="Unit 2" selected>Unit 2</option>
    <option value="Unit 3">Unit 3</option>
</select>


我编辑了我的答案以更好地适应问题,旧答案:

使用禁用 HTML 5 属性。

<select name="srcUnit" id="srcUnit">
    <option value="Unit 1">Unit 1</option>
    <option value="Unit 2" selected>Unit 2</option>
    <option value="Unit 3">Unit 3</option>
</select>
<select name="dstUnit" id="dstUnit">
    <option value="Unit 1">Unit 1</option>
    <option value="Unit 2" disabled>Unit 2</option>
    <option value="Unit 3">Unit 3</option>
</select>

阅读更多并在此处尝试:http://www.w3schools.com/tags/att_option_disabled.asp

使用 javascript 订阅下拉列表的 onchange 事件,并根据需要切换属性。