首页 > 解决方案 > 如何基于单选按钮隐藏和取消隐藏表单字段?

问题描述

我正在尝试实现一个单选按钮,如果单击该按钮,应该会获得更多选项供用户填写。

这是我尝试过的。

<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>

上面的代码不起作用。当我单击单选按钮时,什么也没有发生,表单的一部分总是隐藏的。

标签: javascriptphpforms

解决方案


编辑:我最初误解了这个问题,现在调整了我的答案。

此外,我还包含一个功能,如果单击另一个单选按钮,该功能将隐藏您的输入。

请参阅下面的片段:

//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>


推荐阅读