Rich701 Rich701 - 1 year ago 88
Javascript Question

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!

Answer Source

I've noticed that you don't specify whether or not you can use jQuery. If that's an option, please see one of the other posts as I highly recommend it.

If you cannot use jquery then try the following:

  function setFries(){
    var el = document.getElementById("burger");
      document.getElementById("fries").disabled = false;
     document.getElementById("fries").disabled = true;    

<div><input type="radio" name="o1" id="burger" onchange="setFries();"/>Burger</div>
<div id="yesFries"><input type="checkbox" name="e1" id="fries" disabled="disabled"/>Fries with that?</div>
<div><input type="radio" name="o1" id="pizza" onchange="setFries();"/>Pizza</div>
<div><input type="radio" name="o1" id="hotdog" onchange="setFries();"/>Hot Dog</div>‚Äč

Simple example on jsFiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download