<div class="wrapper">
<form action="">
<h2>Example One</h2>
<label>
<input type="radio" name="Gender" value="Male">
Male
</label>
<label>
<input type="radio" name="Gender" value="Female">
Female
</label>
<label>
<input type="radio" name="Gender" value="Other">
Other
</label>
<input type="text" name="Gender-Type" class="input--hide">
<input type="submit">
</form>
<form action="">
<h2>Example Two</h2>
<label>
Contact Preferences
<select name="contact">
<option>Please select...</option>
<option value="Email">Email</option>
<option value="Phone">Phone</option>
<option value="Pigeon">Pigeon</option>
</select>
</label>
<label class="input--hide js-select" id="Email">
Email
<input type="email">
</label>
<label class="input--hide js-select" id="Phone">
Phone Number
<input type="tel">
</label>
<label class="input--hide js-select" id="Pigeon">
<input type="checkbox">
Make a wish!
</label>
<input type="submit">
</form>
<form action="" class="wombat-form">
<h2>Example Three</h2>
<label>
Favourite Animal
<input type="text" id="favourite-animal">
</label>
<div class="input--hide" id="wombat">
<img src="https://cpb-eu-w2.wpmucdn.com/blogs.ucl.ac.uk/dist/9/186/files/2018/02/Wombat-C-Jack-Ashby.jpg" alt="">
</div>
</form>
</div>
.input--hide {
position: absolute;
left: -9999px;
opacity: 0;
transiton: opacity .3s ease;
}
.input--show {
opacity: 1;
position: static;
}
/* You can ignore this styling */
label { display: block; margin-bottom: 1em; font-weight: bold; } .wrapper { display: flex; justify-content: space-between; } form { background: #e1e1e1; padding: 1em; width: 300px } select, input[type=text] { display: block; } html { font-family: arial; } h2 { color: #bbb; margin: 0 0 1em; font-style: italic; } [type=submit] { appearance: none; background: lightblue; }
// Example One
const $input = $('[name=Gender-Type]');
const $radios = $('input[type=radio][name=Gender]');
$radios.on('change', (e) => {
const value = e.currentTarget.value;
$input
.toggleClass('input--show', value === 'Other')
.attr('required', () => value === 'Other');
});
// Example Two
const $select = $('[name=contact]');
$select.on('change', (e) => {
const value = e.currentTarget.value;
$('.js-select')
.removeClass('input--show')
.find('input')
.attr('required', false);
$('#' + value)
.addClass('input--show')
.find('input')
.attr('required', true);
});
// Example Three
const $animalInput = $('#favourite-animal');
const $wombat = $('#wombat');
$animalInput.on('input', (e) => {
const value = e.currentTarget.value;
const isWombat = value.match(/wombat/i) || false;
$wombat.toggleClass('input--show', isWombat);
});
This Pen doesn't use any external CSS resources.