Skip to content
Advertisement

Function that hides a label depending on radio button

I’m trying to get a function working that hides a label in the form depending on the radio button option selected. Here’s my code so far.

HTML

<form action="">
<input type="radio" id="test" value="first"> first<br>
<input type="radio" id="test" value="second"> second<br>
<input type="radio" id="test"  value="third"> third
</form>

<label class="hidden">Hide this</label>

Javascript

var rbtn = document.getElementById("test");
var x = document.getElementsByClassName("hidden");

function hidelabel() {

  if (rbtn == 'third') {
    x.style.display='none';
}
}

Advertisement

Answer

You must fire your hide function after radio button clicked like this:

document.mainForm.onclick = function(){
    var radVal = document.mainForm.rads.value;
    if (radVal == 'third') {
        document.getElementsByClassName("hidden")[0].style.display = 'none';
    }
}

ps: document.getElementsByClassName returns an array. So you cannot use x.style.display='none';.

Working example: https://jsfiddle.net/5ts0dak4/

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement