HAM
HAM

Reputation: 31

How to hide and unhide form fields based on a radio button?

I'm trying to implement a radio button, which if clicked should get more options for the user to fill in.

Here's what I've tried.

<script>
  function addmentor() {
    if ( document.getElementById("type_Computer").checked ) {
    document.getElementById('nextSetOfComputerOptions').style.display = "";
    } else {
    document.getElementById('nextSetOfComputerOptions').style.display = "none";
    }
}
</script>

<input type="radio" name="type" id="type_computer" value="Computer"  onClick="addmentor()">Add    Mentor</button>
<div id="nextSetOfComputerOptions" style="display:none;">
.
.
</div>

The above code doesn't work. When I am clicking the radio button, nothing happens, the part of the form is always hidden.

Upvotes: 0

Views: 1166

Answers (1)

Aib Syed
Aib Syed

Reputation: 3196

EDIT: I originally misunderstood the question and have now adjusted my answer.

Additionally, I have also included a function that will hide your input if another radio button is clicked.

See the snippet below:

//your checkbox
var checkbox = document.getElementById("type_computer");

//your div
var inputDiv = document.getElementById("nextSetOfComputerOptions");

//function that will show hidden inputs when clicked
function addmentor() {
  if (checkbox.checked = true) {
    inputDiv.style.display = "block";
  }
}

//function that will hide the inputs when another checkbox is clicked
function hideInputDiv() {
  inputDiv.style.display = "none";
}
<input type="radio" name="type" id="type_computer" value="Computer" onChange="addmentor();" ">Add Mentor</input>
<input type="radio" name="type" onClick="hideInputDiv();">Other radio input</input>
<div id="nextSetOfComputerOptions" style="display: none;">
  <input placeholder="PC"></input>
  <input placeholder="Mac"></input>
</div>

Upvotes: 1

Related Questions