Blog>
Snippets

Conditional Form Fields

Demonstrate how to render additional form fields based on previous selections, such as choosing 'other' from a dropdown menu and displaying an additional text input.
document.getElementById('dropdown').addEventListener('change', function(event) {
    var value = event.target.value;
    if (value === 'other') {
        document.getElementById('otherField').style.display = 'block';
    } else {
        document.getElementById('otherField').style.display = 'none';
    }
});
This code adds an event listener to a dropdown element with id 'dropdown'. When the selected option of the dropdown changes, it checks the value of the selected option. If the value is 'other', it will display the additional text input field with id 'otherField'. If it is not 'other', it will hide the 'otherField'.
<!-- HTML structure for dropdown menu and conditional text input field -->
<select id="dropdown">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="other">Other</option>
</select>

<div id="otherField" style="display: none;">
    <label for="otherInput">Please specify:</label>
    <input type="text" id="otherInput" name="otherInput">
</div>
This is the HTML structure required for the code above to work. It includes a dropdown menu with 'other' as one of the options. It also includes a div with an input text field which is initially hidden using inline CSS. The div will be shown or hidden based on the selection in the dropdown menu.