Toggle navigation
☰
Home
HTML
CSS
Scripting
Database
<!DOCTYPE html> <title>My Example</title> <style> .conditional-form-container { max-width: 500px; margin: 40px auto; padding: 30px; background-color: #f9f9f9; border-radius: 8px; border: 1px solid #ddd; font-family: sans-serif; } .conditional-form-container h3 { margin-top: 0; text-align: center; } .form-group { margin-bottom: 20px; } .form-group label { display: block; margin-bottom: 5px; font-weight: 500; } .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 1rem; box-sizing: border-box; } /* This is the field to be hidden/shown */ .conditional-field { display: none; /* Hidden by default */ margin-top: 15px; /* Add some space when it appears */ border-top: 1px dashed #ccc; padding-top: 15px; } .conditional-field.visible { display: block; /* Shown when it has the 'visible' class */ } </style> <div class="conditional-form-container"> <h3>Contact Us</h3> <form id="conditionalForm" action="#" method="post"> <div class="form-group"> <label for="topic">How can we help you?</label> <!-- This is the trigger element --> <select id="topic" name="topic" required> <option value="">Select a topic...</option> <option value="support">Technical Support</option> <option value="sales">Sales Inquiry</option> <option value="feedback">General Feedback</option> <option value="other">Other...</option> </select> </div> <!-- This field is conditional and hidden by default --> <div class="form-group conditional-field" id="other-topic-group"> <label for="other-topic">Please specify</label> <input type="text" id="other-topic" name="other_topic"> </div> <div class="form-group"> <label for="message">Your Message</label> <textarea id="message" name="message" required></textarea> </div> <button type="submit">Send Message</button> </form> </div> <script> const topicSelect = document.getElementById('topic'); const otherTopicGroup = document.getElementById('other-topic-group'); const otherTopicInput = document.getElementById('other-topic'); if (topicSelect && otherTopicGroup && otherTopicInput) { topicSelect.addEventListener('change', () => { // Check if the selected value is 'other' if (topicSelect.value === 'other') { // Show the conditional field otherTopicGroup.classList.add('visible'); // Make the input required only when it's visible otherTopicInput.required = true; } else { // Hide the conditional field otherTopicGroup.classList.remove('visible'); // Make the input not required when it's hidden otherTopicInput.required = false; } }); } </script>