gpt4 book ai didi

javascript - 使用复选框禁用多项选择

转载 作者:行者123 更新时间:2023-11-30 15:39:47 26 4
gpt4 key购买 nike

我的代码很乱,很抱歉。

JS 有效,但仅适用于第一次选择;我想让用户输入一个时间,但是如果用户那天不工作,我想禁用四个选择框。不幸的是,我不知道在 JS 中的何处添加其他选择。

还有另一个脚本可以填充选择的其余选项。我到目前为止的代码:

if (document.getElementById('holiday_check').checked)
document.getElementById('holiday_time_h1').setAttribute('disabled', 'disabled');

function closed_holiday() {
if (document.getElementById('holiday_check').checked)
document.getElementById('holiday_time_h1').setAttribute('disabled', 'disabled');
else
document.getElementById('holiday_time_h1').removeAttribute('disabled');
}
<div> 
<span>Opening Time:</span>
<select id="holiday_time_h1"><option>00</option></select>
:
<select id="holiday_time_m1"><option>00</option></select>

<span>Closing time</span>
<select id="holiday_time_h2"><option>00</option></select>
:
<select id="holiday_time_m2"><option>00</option></select>

<input id="holiday_check" class="check" type="checkbox" onchange="closed_holiday();">Closed</input>

</div>

最佳答案

有多种方法可以中止这个问题。最常见和可忍受的方法是遍历每个选择并一一禁用它们。

首先,您需要为每个要禁用的选择元素获取一个数组。您可以将它们附加到同一类;让我们说“假期”,然后使用选择器 getElementsByClassName() 将它们全部放入一个数组中或 querySelector() .

完成后,您将遍历该元素数组,并在用户通过复选框元素选择禁用时禁用它们。

const mySelectElements = document.getElementsByClassName("holiday");
const holidayCheck = document.getElementById("holiday_check");

function closed_holiday(){
for(let selectElement of mySelectElements){
if(holidayCheck.checked){
selectElement.setAttribute('disabled', 'disabled');
}
else{
selectElement.removeAttribute('disabled');
}
}
}
<div> 
<span>Opening Time:</span>
<select class="holiday" id="holiday_time_h1"><option>00</option></select>
:
<select class="holiday" id="holiday_time_m1"><option>00</option></select>

<span>Closing time</span>
<select class="holiday" id="holiday_time_h2"><option>00</option></select>
:
<select class="holiday" id="holiday_time_m2"><option>00</option></select>

<input id="holiday_check" class="check" type="checkbox" onchange="closed_holiday();">Closed</input>

</div>

关于javascript - 使用复选框禁用多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40991164/

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