簡體   English   中英

Javascript在復選框勾選上啟用文本字段

[英]Javascript enable textfield on checkbox tick

我有這個HTML代碼:

<input type="checkbox" onclick="document.getElementById('directory_entry_name').disabled=this.checked;" name="directory_entry" id="directory_entry" />

<strong>Name: </strong><input type="text" name="directory_entry_name" id="directory_entry_name" disabled="disabled" />

文本框被禁用,我試圖這樣做,當復選框被選中時,它將啟用文本框,當它再次被取消選中時,它將禁用文本框。

如果我使用它可以工作:

<input type="checkbox" onclick="document.getElementById('directory_entry_name').disabled=false;" name="directory_entry" id="directory_entry" />

但是當它未經檢查時,它不會重新禁用文本框。

這是相反的。 放一個! (不)在那里。

document.getElementById('directory_entry_name').disabled=!this.checked;

瀏覽器檢查是否有屬性已禁用,而不是值: 禁用屬性說明因此,在禁用或啟用輸入的功能中,您應添加和刪除“已禁用”屬性。 你可以用jQuery .removeAttr()和.attr()來做到這一點。

所以函數看起來像這樣:

function SetInputActive(checkbox) {
if($(checkbox).is(':checked')) $('directory_entry_name').removeAttr("disabled");
else $('directory_entry_name').attr("disabled", "disabled");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM