gpt4 book ai didi

javascript - 如何在html中建立不同select标签的option标签之间的关系

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

我在 HTML 中有三个带有选项标签的选择标签。我想在不同选择标签的选项标签之间建立关系。

EDIT-1

当我从 select name="reference"中选择 Reference-1 时,然后从 select name="from"中选择 2014-10-10 07:17:00 和 2014-10-10 08:46:00 并选择 name="to"应该只出现在下拉列表中。当我选择 Reference-2 时,2014-09-01 10:00:00 和 2014-09-01 11:00:00 应该只出现在 的下拉列表中fromto 选择标签。我的 html 代码是-

<form method="post">
Select Reference:
<select name="reference">
<option value="Select">Select</option>
<option value="Reference-1">Reference-1;</option>
<option value="Reference-2">Reference-2</option>
<option value="Reference-3">Reference-3</option>
<option value="Reference-4">Reference-4</option>
</select>
From Date:
<select name="from">
<option value="Select">Select</option>
<option value="2014-10-10 07:17:00">2014-10-10 07:17:00</option>
<option value="2014-09-01 10:00:00">2014-09-01 10:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 10:00:00</option>
</select>
To Date:
<select name="to">
<option value="Select">Select</option>
<option value="2014-10-10 08:46:00">2014-10-10 08:46:00</option>
<option value="2014-09-01 11:00:00">2014-09-01 11:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 11:00:00</option>
</select><br>

<b>Select Date to be compared</b>
<p>Date: <input type="text" id="datepicker"></p>
<input type="submit" value="Submit"><br>
</form>

最佳答案

reference select 元素中获取所选选项的索引,然后禁用 fromto select 元素中除该选项之外的所有选项与您从 reference 选择选项中获得的上一个索引的索引。

javaScript 解决方案:

var reference = document.getElementsByName("reference")[0];

var fromSelect = document.getElementsByName("from")[0];
var toSelect = document.getElementsByName("to")[0];

reference.onchange = function(){
var selectedIndex = this.selectedIndex;
for(var i = 1; i <= fromSelect.length; i++){
if(i != selectedIndex){
fromSelect.getElementsByTagName("option")[i].disabled = true;
toSelect.getElementsByTagName("option")[i].disabled = true;
} else{
fromSelect.getElementsByTagName("option")[i].disabled = false;
toSelect.getElementsByTagName("option")[i].disabled = false;
}
}
};

jsFiddle

jQuery 解决方案:

$("select[name='reference']").on("change", function(){
var $fromSelect = $("select[name='from']");
var $toSelect = $("select[name='to']");
var selectedIndex = $(this).children("option:selected").index();
$fromSelect.children("option").removeAttr("disabled");
$toSelect.children("option").removeAttr("disabled");
$fromSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
$toSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
});

jsFiddle

关于javascript - 如何在html中建立不同select标签的option标签之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403639/

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