Search code examples
javascriptradio-buttonchecked

".check" for radio in JS


here's my code:

document.getElementById("frequencyweekly").checked = function() {
    document.getElementById("newsoptions").className = "activesubscription";
};

    <div id="newsoptions">
        <input type="radio" id="frequencyweekly" name="newsletterfrequency">
        <label for="frequencyweekly">Weekly</label>

        <input type="radio" id="frequencymonthly" name="newsletterfrequency">
        <label for="frequencymonthly">Monthly</label>
    </div>

I would like my .newsoptions div have class .activesubscription if #frequencyweekly button is checked. How should I do that?


Solution

  • checked is a boolean, not an event that fires a function, so you probably want

    if ( document.getElementById("frequencyweekly").checked ) {
        document.getElementById("newsoptions").className = "activesubscription";
    }
    

    if you want that in an event handler it would be

    var box  = document.getElementById("frequencyweekly"),
        elem = document.getElementById("newsoptions");
    
    box.addEventListener('change', function() {
        if ( this.checked ) {
            elem.classList.add("activesubscription");
        } else {
            elem.classList.remove("activesubscription");
        }
    }, false);