如何实现选中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
changeevent on all radio buttons in the same group (sharednameattribute). - When the Other option (value="c") is selected, we set the text box's display to
blockto 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
相关产品推荐
相关产品推荐

