Search code examples
javascripthtmlradio-button

Get radio button value onload and hide or show div


I have the following jsfiddle setup:

http://jsfiddle.net/cvn6n/

Based on the radio selection a div is hidden or displayed (if audi is selected the div is hidden and if any other value is selected the div is displayed). The problem that I have is that I need to detect the initial value (onload) of the radio button and accordingly hide or display the div.

Audi <input type="radio" name="car" id="audi" value="3" checked="checked" onclick="toggle(this)">
<br />
Merc <input type="radio" name="car" id="merc" value="3" onclick="toggle(this)">
<br />
BMW <input type="radio" name="car" id="bmw" value="3" onclick="toggle(this)">
<br /><br />
<div id="testdiv">
Not Audi
</div>

var t = document.getElementById('testdiv');

t.style.visibility = 'visible';                
function toggle(switchElement) {
    if (switchElement.id != 'audi'){
        t.style.display = 'inline';
    }else{
        t.style.display = 'none';
    }
}

Thanks for the help in advance.

ps. no jquery please just pure js solution


Solution

  • [].forEach.call( document.forms.carform.car, function(radio){
          if( radio.checked ) {
              toggle( radio );   
          }
    });
    

    http://jsfiddle.net/cvn6n/1/