禁用文本框无效

时间:2016-08-31 15:26:34

标签: javascript

我正在写小表,所以jQuery在这里已经没有了。

问题是,为什么这段代码不想工作?



function isChecked() {
  if (document.getElementById("priceCall").checked) {
    document.getElementById("mailingPrice").setAttribute("disabled", false);
  } else {
    document.getElementById("mailingPrice").setAttribute("disabled", true);
  }
}

var priceCall = document.getElementById("priceCall");
priceCall.addEeventListener("change", isChecked);

<h2>Costs of sending? (point if yes)</h2>
Mailing price:
<input id="mailingPrice" type="text" disabled>
<input type="checkbox" id="priceCall" onchange="isChecked()">
<br>
<br>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您应该直接在元素上设置disabled属性。例如:

element.disabled = true;

如果您在代码中更改了它,它可以正常工作:

function isChecked() {
  if (document.getElementById("priceCall").checked) {
    document.getElementById("mailingPrice").disabled = false;
  } else {
    document.getElementById("mailingPrice").disabled = true;
  }
}

var priceCall = document.getElementById("priceCall");
priceCall.addEventListener("change", isChecked);
<h2>Costs of sending? (point if yes)</h2>
Mailing price:
<input id="mailingPrice" type="text" disabled>
<input type="checkbox" id="priceCall" onchange="isChecked()">
<br>
<br>

这只是额外的一点,但你可以简化这个:

function isChecked() {
  document.getElementById("mailingPrice").disabled = !this.checked;
}

var priceCall = document.getElementById("priceCall");
priceCall.addEventListener("change", isChecked);
<h2>Costs of sending? (point if yes)</h2>
Mailing price:
<input id="mailingPrice" type="text" disabled>
<input type="checkbox" id="priceCall" onchange="isChecked()">