[英]Keep input disabled until correct option is selected in html
我需要在选择“截止日期”选项之前禁用“日期”输入。 我尝试了以下方法,但无法正常工作。 有什么建议么?
码
<Select>
<option onselect="document.getElementById('deadline').disabled = false;">Deadline date</option>
<option>Monthly</option>
</Select>
<input id="deadline" type="date" disabled>
您需要将事件处理程序附加到您选择的change
事件上,然后使用this.value
检查其值。
最后,将输入的disabled
属性相应地设置为true
或false
。
document.getElementsByTagName('select')[0].onchange = function() { document.getElementById('deadline').disabled = this.value != 'Deadline date'; }
<select> <option>Deadline date</option> <option>Monthly</option> </select> <input id="deadline" type="date" disabled>
在dropdown
更改事件中,您可以使用匹配条件添加或删除这样的attribute
。
$("select").change(function() { if ($(this).val() == 'Deadline date') $('#inpTest').removeAttr('disabled'); else $('#inpTest').attr("disabled", true); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <Select> <option>---select---</option> <option>Deadline date</option> <option>Monthly</option> </Select> <input type="date" disabled="disabled" id='inpTest'>
应该这样:
function validate() { var dropdown = document.getElementById('dropdown'); var selectedOption = dropdown.options[dropdown.selectedIndex].value; var input = document.getElementById('date'); if (selectedOption == "enabled") { input.removeAttribute('disabled'); } else { input.setAttribute('disabled', 'disabled'); } }
<select id="dropdown" onchange="validate()"> <option value="disabled">Pick something</option> <option value="enabled">Deadline date</option> <option value="disabled">Monthly</option> </select> <input type="date" id="date" disabled="disabled">
您的问题是< option
>上的事件未触发。 请检查以下代码。
<select id="selectedOption" onchange="myFunction()">
<option>select</option>
<option>Deadline date</option>
<option>Monthly</option>
</select>
<input id="deadline" type="date" disabled>
<script>
function myFunction() {
if (document.getElementById("selectedOption").value == "Deadline date") {
document.getElementById("deadline").disabled = false;
} else {
document.getElementById("deadline").disabled = true;
}
}
</script>
希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.