You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现选中Other单选框时才显示HTML输入框?

Solution to Show Text Box Only When "Other" Radio is Selected

Absolutely! You can implement this with simple JavaScript to toggle the visibility of your text input based on which radio button is selected. Here's how to update your code:

<html>
<body>
<div class="form-group">
  <input type="radio" name="option" value="a"> Missing deadline.<br>
  <input type="radio" name="option" value="b"> Unsatisfied with the work.<br>
  <input type="radio" name="option" value="c"> Other<br>
  <!-- Add the hidden text box here -->
  <input type="text" id="otherInput" placeholder="Please specify other reason" style="display:none; margin-top: 8px;">
</div>

<script>
// Get all radio buttons with name "option"
const radioButtons = document.querySelectorAll('input[name="option"]');
// Get the text input element
const otherInput = document.getElementById('otherInput');

// Add change event listener to each radio button
radioButtons.forEach(radio => {
  radio.addEventListener('change', () => {
    // Show the text box only if "Other" is selected
    if (radio.value === 'c' && radio.checked) {
      otherInput.style.display = 'block';
    } else {
      otherInput.style.display = 'none';
      // Optional: Clear the input when hiding it to avoid leftover text
      otherInput.value = '';
    }
  });
});
</script>
</body>
</html>

Key Details:

  • The text box starts hidden using style="display:none".
  • We listen for the change event on all radio buttons in the same group (shared name attribute).
  • When the Other option (value="c") is selected, we set the text box's display to block to show it. For any other selection, we hide it again and optionally clear its value.

This approach works seamlessly across all modern browsers, and you can tweak the styling (like margin or padding) to match your form's design.

内容的提问来源于stack exchange,提问作者Jacel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:04:20