【问题标题】:Hide a div based on select radio button in a form根据表单中的选择单选按钮隐藏 div
【发布时间】:2019-04-11 23:04:08
【问题描述】:

我有一个表格,您必须在两个 input type="radio" 之间进行选择,一个说 yes,另一个说 no
当您选择 no 选项时,我想让表单中可见的 div 消失。我尝试从我在互联网上阅读的其他帖子中复制一些 JS,但对我没有任何效果。
有人可以告诉我应该使用的代码吗?可以是 JS、PHP 或 CSS。

这是我的代码:

<div class="form-radio">
<label for="sons" class="radio-label">Question:</label>
<div class="form-radio-item">
<input type="radio" name="yes" id="yes" checked value="YES">
<label for="hsi">YES</label>
<span class="check"></span>
</div>
<div class="form-radio-item">
<input type="radio" name="no" id="no" value="NO">
<label for="hno">NO</label>
<span class="check"></span>
</div>
</div>

<div id="hello">
You clicked on NO, so this div disappears.    
</div>

【问题讨论】:

  • 您尝试了哪些代码使其工作?您提到您尝试了一些代码,但它似乎不在您的帖子中。
  • 您的单选按钮甚至不能用作单选按钮(当您单击一个时,另一个保持选中状态) - 因为它们具有不同的 name 属性。
  • @RobinZigmond 所以你说首先,我应该更改输入的name,使它们具有相同的?
  • Stack Overflow 不是代码编写服务。不要在这里问这样的问题。 stackoverflow.com/help/on-topic
  • 是的,这就是 Robin 的意思

标签: javascript html forms css


【解决方案1】:

您需要将事件侦听器添加到您的输入中,并且您应该将两个单选按钮的名称更改为相同的名称。我在下面使用了inputs。然后,我根据单击的选择切换#hello 元素上的display 样式。

const hello = document.getElementById('hello');

document.getElementById('yes')
  .addEventListener('click', function() {
    hello.style.display = null;
  });
  
document.getElementById('no')
  .addEventListener('click', function() {
    hello.style.display = 'none';
  });
<div class="form-radio">
<label for="sons" class="radio-label">Question:</label>
<div class="form-radio-item">
<input type="radio" name="inputs" id="yes" checked value="YES">
<label for="hsi">YES</label>
<span class="check"></span>
</div>
<div class="form-radio-item">
<input type="radio" name="inputs" id="no" value="NO">
<label for="hno">NO</label>
<span class="check"></span>
</div>
</div>

<div id="hello">
You clicked on NO, so this div disappears.    
</div>

【讨论】:

  • Stack Overflow 不是代码编写服务。不要回答这些离题的问题。该问题最终将被删除。
  • 我试过这样做,但它不起作用。也许是因为我的表单中有其他输入?
【解决方案2】:

您可以使用纯 CSS 来实现这一点。不知道我的解决方案是否合适,因为我不知道您页面的其余部分的结构。

.form-radio {
  position: relative;
  padding-bottom: 2rem;
}

input#no ~ #floatingDescription  {
  position: absolute;
  bottom: 0px;
  left: 0px;
  display: block;
}

input#no:checked ~ #floatingDescription {
  display: none;
}
<!DOCTYPE html>
<hml>

<body>
  <div class="form-radio">
    <label for="sons" class="radio-label">Question:</label>
    <div class="form-radio-item">
      <input type="radio" name="answer" id="yes" checked>
      <label for="hsi">YES</label>
    </div>
    <div class="form-radio-item">
      <input type="radio" name="answer" id="no">
      <label for="hno">NO</label>
      <div id="floatingDescription">You clicked on NO, so this div disappears.</div>
    </div>
  </div>

</body>
</html>

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 2012-02-18
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多