<h1>Conditional forms with data-attributes</h1>
<p>This form has conditional elements. Try it. The show/hide logic is defined in HTML <code>data-master</code> and <code>data-master-value</code> attributes.</p>
<p>If an element (the "slave") in a form has a data-master attibute, its value should be an ID of a form control (the "master"). Depending on the type of the master (radio, select, etc) either the checked state or value will be used to determine if the slave should be shown.</p>
<p>Slaves of an invisible master will be hidden automatically, so dependency chaining is really easy.<p>
<form>
<fieldset>
<legend>Stuff</legend>
<p>
<label for="a">Label</label>
<input id="a">
</p>
<p>
<input id="b_1" name="b" type="radio">
<label for="b_1">Check me</label>
<input id="b_2" name="b" type="radio">
<label for="b_2">Or me</label>
</p>
<p data-master="b_1">
<label for="c">Please select</label>
<select id="c">
<option></option>
<option>one</option>
<option>two</option>
</select>
</p>
<p data-master="c" data-master-value="two">
<strong>Really? Two?</strong>
</p>
<p data-master="b_2">
<label for="d">Please explain</label>
<textarea></textarea>
</p>
</fieldset>
CSS
form p {
margin: 0;
padding: 10px;
}
form p label {
display: inline-block;
width: 200px;
}
form p input[type="radio"]:first-child {
margin-left: 200px;
}
form p input[type="radio"] + label {
width: auto;
display: inline;
margin: 0 10px 0 0;
}
JavaScript
// Every time some element is changed
$('form').on('change', function() {
// Look for all the slaves
$('[data-master]').each(function() {
var slave = $(this);
// Find the corresponding master
var master = $('#' + slave.data('master')).first();
// If the master is invisible, hide the slave
if (!master.is(':visible')) {
slave.hide();
return;
}
// Toggle the slave visibility based on the master's type and value
switch(master.attr('type')) {
case 'radio':
case 'checkbox':
slave.toggle(master.prop('checked'));
break;
default:
slave.toggle(master.val() === slave.data('master-value'));
break;
}
});
// Initialize the form immediately
}).trigger('change');
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.