简体   繁体   中英

How to disable input unless a radio button is clicked?

I'm not so familiar with Javascript and I know this to be a very easy question, but I can't figure out where I'm going wrong.

I'm trying to disable two input fields unless a radio button with the id "custom" is selected.

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 />

Javascript

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;
    }
}

Here is my code in JSFiddle.

Multiple issues:

  1. Use onclick instead of onchange , and make sure to assign the event handler to all radio buttons, not just custom , otherwise clicking away from custom will not disable the input field. See also: OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

  2. It's getElementById , not getElementsById .

  3. There's no document.getElementByName .

  4. In jsfiddle, define a function with window.foo = function() {...} , not function foo() {...} (because that code is embedded in onload ).

FYC: http://jsfiddle.net/MEsGH/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM