2016-08-31 58 views
0

我正在寫一個小表單,所以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>

+0

請注意,addEeventListener存在拼寫錯誤。 – Tushar

回答

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()">