[英]How to disable input unless a radio button is clicked?
我對Javascript不太熟悉,我知道這是一個非常簡單的問題,但是我無法弄清楚哪里出了問題。
我試圖禁用兩個輸入字段,除非選擇了ID為“ custom”的單選按鈕。
的HTML
<input type="radio" name="period" value="week" /> Weekly
<input type="radio" name="period" value="fortnight" /> Fortnightly
<input type="radio" name="period" value="month" /> Monthly
<input type="radio" name="period" value="quarter" /> Quarterly
<input type="radio" name="period" value="year" /> Annually
<input type="radio" name="period" id="custom" value="one-time" onchange="datedis()"/
<input type="date" name="from" disabled /> to <input type="date" name="to" disabled />
Java腳本
function datedis() {
if(document.getElementsById("custom").checked) {
document.getElementsByName("from").disabled = false;
document.getElementsByName("to").disabled = false;
} else {
document.getElementsByName("from").disabled = true;
document.getElementsByName("to").disabled = true;
}
}
這是我在JSFiddle中的代碼。
多個問題:
使用onclick
而不是onchange
,並確保將事件處理程序分配給所有單選按鈕,而不僅僅是custom ,否則單擊custom不會禁用輸入字段。 另請參見: 單選按鈕的OnChange事件處理程序(INPUT type =“ radio”)不能用作一個值
它是getElementById
,而不是getElementsById
。
沒有document.getElementByName
。
在jsfiddle中,使用window.foo = function() {...}
定義一個函數,而不是function foo() {...}
(因為該代碼已嵌入onload
)。
FYC: http : //jsfiddle.net/MEsGH/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.