gpt4 book ai didi

javascript - 选择更改仅选择两次

转载 作者:行者123 更新时间:2023-11-28 07:35:46 25 4
gpt4 key购买 nike

我有 2 个下拉菜单。当您从第一个下拉列表 $("#HandlingUnit") 中选择处理单元时,它应该读取所​​选选项组的标签文本,然后根据选项的文本更改第二个......

示例场景:

  1. 从 $("#HandlingUnit") 中选择 2222,它会读取 optgroup 标签“Cases”并将 $("#HUType") 更改为“Cases”
  2. 从 $("#HandlingUnit") 中选择 P00001,它会读取 optgroup 标签“Pallets”并将 $("#HUType") 更改为“Pallets”
  3. 从 $("#HandlingUnit") 中选择 1111(或 2222),它不会更改为 Cases。

这对于两次更改非常有用,但是第三次​​时,第二个下拉列表不会更改。

<label class="label_long" for="HandlingUnit">Handling Unit:</label>
<select id="HandlingUnit" required="" name="HandlingUnit">
<optgroup id="Pallets" label="Pallets">
<option value="P00001">P00001</option>
</optgroup>
<optgroup id="Cases" label="Cases">
<option value="1111">1111</option>
<option value="2222">2222</option>
</optgroup>
</select>

<label class="label_long" for="HuType">Handling Unit Type: </label>
<select id="HUType" name="HUType">
<option value="1" name="Pallets"> Pallets </option>
<option value="0" name="Case" selected="selected"> Cases </option>
<option value="3" name="Items"> Items </option>
</select>

Javascript/jQuery:

$(document).on("change", "select#HandlingUnit", function() {
var selected = $(":selected", this).parent().attr('label');

$("#HUType").find("option:selected").removeAttr("selected");

$("#HUType option").filter(function() {
console.log(this.text.trim() + " >> " + selected);
return this.text.trim() == selected;
}).attr("selected", true)
});

JSFiddle

编辑:JSFiddle 没有响应它在我的应用程序中的表现,所以我认为可能发生了更大的事情......如果我发现任何东西,调查它会报告回来。

最佳答案

您可以使用.val(function)

A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

代码

$(document).on("change", "select#HandlingUnit", function() {
var selected = $(":selected", this).parent().attr('label');

//Find option with selected label and set its value
$("#HUType").val(function(){
return $(this).find('option[name="' + selected +'"]').val();
});
});

$("select#HandlingUnit").trigger("change"); //Trigger on page load

DEMO

关于javascript - 选择更改仅选择两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28610828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com