JSFiddle - React, Tailwind, and code Playground
by ninty9notout
HTML
<h1>Sam's epic form</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<form action="#" method="post">
<p>
<label for="field-1">My favourite show is: </label><br>
<select id="field-1" name="show">
<option value="simpsons">The Simpsons</option>
<option value="futurama">Futurama</option>
</select>
</p>
<p class="hide" id="option-simpsons">
<label for="field-simpsons">My favourite Simpson is: </label><br>
<select id="field-simpsons" name="simpson-characters">
<option value="bart">Bart</option>
<option value="homer">Homer</option>
</select>
</p>
<p class="hide" id="option-futurama">
<label for="field-futurama">My favourite Futurama character is: </label><br>
<select id="field-futurama" name="futurama-characters">
<option value="bender">Bender</option>
<option value="fry">Fry</option>
</select>
</p>
<p><button type="submit" id="submit">Submit</button></p>
</form>
CSS
h1 {
font-size: 2em;
}
h1, p {
margin-bottom: 1em;
}
/**
* Make the elements with the class "hide" hidden
*/
.hide {
display: none;
}
JavaScript
$(document).ready(function() {
// When the field with id "field-1" changes
$('#field-1').bind($.browser.msie ? 'propertychange': 'change', function(e) {
// Hide the elements with the class "hide"
$('.hide').hide();
// Get the value from this field
// $(this) in this instance refers to field with id field-1
var show = $(this).val();
// Show the element with the id "option-[selected]"
// where [selected] will be the value of the first field
// ie. simpsons or futurama
$('#option-' + show).show();
});
// Attach a onclick handler to the submit button
$('#submit').click(function() {
var show = $('#field-1').val();
var char = $('#field-' + show).val();
alert("Your favourite show is: " + show + "\nAnd your favourite character is: " + char);
return false;
});
});