JSFiddle - React, Tailwind, and code Playground
HTML
<form action="#" method="post" id="fruitMeatForm">
<fieldset>
<legend>
About your tastes
</legend>
<label for="preference">What do you prefer ?</label>
<select id="preference" name="preference">
<option value="">- Choose -</option>
<option value="fruit">Fruit</option>
<option value="meat">Meat</option>
</select>
</fieldset>
<fieldset id="fruitField" class="hidden">
<legend>
About fruits
</legend>
<label for="fruit">Depending of your favorite color, what is your favorite fruit ?</label>
<input type="text" name="fruit" id="fruit" value="none" />
</fieldset>
<fieldset id="meatField" class="hidden">
<legend>
About meat
</legend>
<label for="fruit">Depending of your favorite color, what is your favorite meat ?</label>
<input type="text" name="meat" id="meat" value="none" />
</fieldset>
<button type="submit">
Send my preferences
</button>
</form>
CSS
.hidden {
display: none;
}
JavaScript
/*
* A listener on the 'change' event on our select tag
*/
document.querySelector('#preference').addEventListener('change', function() {
/*
* We hide all the fields that needs to be hidden
*/
['#fruitField','#meatField'].forEach(function(value) {
document.querySelector(value).className = 'hidden';
document.querySelector(value).value = 'none';
});
/*
* We show the field depending on the value currently selected
*/
if (this.value !== '') {
document.querySelector('#' + this.value + 'Field').className = '';
document.querySelector('#' + this.value).value = '';
}
}, false);