How to grey out checkbox unless radio button is selected?

Rich701 picture Rich701 · Oct 2, 2012 · Viewed 19.5k times · Source

very new to javascript, but any help to get me started would be appreciated. I have a simple form:

<div><input type="radio" name="o1" id="burger" />Burger</div>
<div id="yesFries"><input type="checkbox" name="e1" id="fries" />Fries with that?</div>
<div><input type="radio" name="o1" id="pizza" />Pizza</div>
<div><input type="radio" name="o1" id="hotdog" />Hot Dog</div>

I want the "Fries" checkbox greyed out unless the "Burger" radio button is selected. I'm not sure if Javascript or CSS is the best way to do it. Thanks in advance!

Answer

kristopher picture kristopher · Oct 2, 2012

what you want to do is set the elements disabled, until the state of the radio changes, that'd be done with javascript, and then you'd add/remove the disabled class in the onchange of the radio button.

What javascript libraries are you considering using? jQuery would make this fairly simple.

$('#burger').change( function () {
    if ($('#burger').checked() ) {
        $('#fries').removeClass('disabled');
    } else {
        $('#fries').addClass('disabled');
    }
});