如何基于下拉选择框显示条件内容?(HTML+JavaScript)
Fixing the Conditional Display Issue for Your Select Field
Let's work through why your otherFieldDiv is always showing, no matter which option you pick. The core issue here boils down to script execution timing and missing initial state setup. Here's how to fix it properly:
First, Let's Spot the Root Problems
- Your
otherFieldDivis set to display by default in the HTML, and if your jQuery code runs before the DOM is fully loaded, the initialtrigger("change")call won't fire correctly to hide it. - You’re referencing an element
#otherFieldin your script that doesn’t exist in your provided HTML — while this won’t break the display logic, it’s unnecessary noise we can clean up.
Corrected Working Code
Here’s the revised version that behaves exactly as you want:
<div class="form-group"> <label for="seeAnotherField">Do You Want To See Another Content?</label> <select class="form-control" id="seeAnotherField"> <option value="no">No Way.</option> <option value="yes">Absolutely!</option> </select> </div> <!-- Add inline style to hide by default --> <div class="form-group" id="otherFieldDiv" style="display: none;"> This text should show up if "Absolutely" is selected </div> <script type="text/javascript"> // Wrap code in document ready to ensure all elements exist first $(document).ready(function() { $("#seeAnotherField").change(function() { if ($(this).val() === "yes") { $('#otherFieldDiv').show(); // Uncomment these lines if you add the #otherField element later // $('#otherField').attr('required', ''); // $('#otherField').attr('data-error', 'This field is required.'); } else { $('#otherFieldDiv').hide(); // $('#otherField').removeAttr('required'); // $('#otherField').removeAttr('data-error'); } }); // Trigger change to set the correct initial state $("#seeAnotherField").trigger("change"); }); </script>
Key Fixes Breakdown
- DOM Ready Wrapper: By putting your script inside
$(document).ready(), we make sure jQuery only interacts with elements after they’ve fully loaded. This guarantees thechangeevent is bound correctly and the initialtriggerworks as intended. - Initial Hidden State: Adding
style="display: none;"tootherFieldDivensures it’s hidden by default, matching the default "No Way." selection. - Cleaned Unused Code: I commented out lines referencing
#otherFieldsince that element isn’t present in your HTML — feel free to uncomment them if you add that field later.
Quick Testing Tip
If you still run into issues, double-check that jQuery is loaded before your script (e.g., include it from a CDN in your <head> or right before the closing </body> tag).
内容的提问来源于stack exchange,提问作者Marko I.
相关产品推荐
相关产品推荐

