Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grey out checkbox unless radio button is selected?

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!

like image 658
Rich701 Avatar asked Oct 02 '12 17:10

Rich701


2 Answers

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');
    }
});
like image 108
kristopher Avatar answered Oct 05 '22 06:10

kristopher


Actually with a bit CSS3 you can mock up a very simplistic solution. Here we don't gray the button out, but you make it visible just if the checkbox is checked. But, we could also gray it out with a bit more of CSS on top of this example. You will always have to consider what kind of support you want to offer. But if you are fine with it working on modern browsers, just give it a go.

Here's the HTML

<label>
    <input type="checkbox" name="test" />
    <span>I accept terms and cons</span><br><br>
    <button>Great!</button>
</label>

Here's the CSS

button { display: none}
:checked ~ button {
    font-style: italic;
    color: green;  
    display: inherit;
}

And here's the DEMO http://jsfiddle.net/DyjmM/

like image 36
2682562 Avatar answered Oct 05 '22 08:10

2682562