首页 > 解决方案 > 即使 java 脚本应该启用它,文本框仍然处于禁用状态

问题描述

我在这里有一个很简单的问题,但它让我很头疼 -

document.getElementById("yourText").disabled = true;
document.getElementById('yourBox').onchange = function() {
  document.getElementById('yourText').enabled = this.checked;
};
<div class="form-group">
  <label asp-for="IsGate"></label>
  <input type="checkbox" id="yourBox" asp-for="IsGate">
</div>
<div class="form-group">
  <label asp-for="Condition"></label>
  <input type="text" id="yourText" asp-for="Condition">
</div>

这应该在选中时启用文本框IsGate,并在未选中时禁用它。在默认情况下将其设置为禁用后,即使更改了复选框,它也会保持不变。

在此处输入图像描述

这里出了什么问题?

标签: javascripthtmlasp.net-core

解决方案


.enabled不是有效属性。使用 always.disabled!this.checked反转逻辑

const el_yourText = document.getElementById('yourText');
const el_yourBox  = document.getElementById('yourBox');

el_yourText.disabled = true;

el_yourBox.addEventListener('change', function() {
  el_yourText.disabled = !this.checked;
});
<div class="form-group">
  <label asp-for="IsGate"></label>
  <input type="checkbox" id="yourBox" asp-for="IsGate">
</div>
<div class="form-group">
  <label asp-for="Condition"></label>
  <input type="text" id="yourText" asp-for="Condition">
</div>


推荐阅读