Home > OS >  Javascript Hidden Text Field Radio Button
Javascript Hidden Text Field Radio Button

Time:12-17

I have a function that is only halfway working right now. My goal is to have a hidden text box appear in the form if a specific radio button is selected and if it is unselected for the text box to disappear again. My script is only showing the hidden field when the specific radio button is selected, but when I select a different radio button it does not hide it again. Here is the function:

function showHideOther() {
        var radioButton = document.getElementById("master");
        var text = document.getElementById("dependent");
if (radioButton.value = "Other") {
            text.style.display="block";
        } else {
            text.style.display="none";
        }
    }

How would I alter this function to get the text field to hide when the radio button is no longer selected?

CodePudding user response:

if (radioButton.value = "Other") { needs to be if (radioButton.value === "Other") {, and you'll need a reference to which radio button was actually clicked, so you'll probably want to pass the event and get e.target:

function showHideOther(e) {
        var radioButton = e.target
        var text = document.getElementById("dependent");
        if (radioButton.value === "Other") {
            text.style.display="block";
        } else {
            text.style.display="none";
        }
}
#dependent {
    display: none;
}
<label for="other"><input onchange="showHideOther(event)" id="other" name="a" value="Other" type="radio"/>Other</label>
<label for="master"><input onchange="showHideOther(event)" id="a1" name="a" value="Something" type="radio"/>Something</label>

<div id="dependent">The text</div>

CodePudding user response:

radioButton.checked property will be helpful for hide and show

        var radioButton = document.getElementById("master");
        var text = document.getElementById("dependent");
if (radioButton.value == "Other" && radioButton.checked) {
            text.style.display="block";
        } else {
            text.style.display="none";
        }
    }
  • Related