JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Some web form</h2>
Parent field:
<input name="BI" type="text" />
<div class="showwhenBI">
<h2>More fields</h2>
<div>
<p>Dependent fields, like europe-only, male-only, or 18+ fields</p>
<p><input value="" /></p>
<p><input value="" /></p>
<p><input value="" /></p>
</div>
</div>
JavaScript
jQuery.fn.showWhen = function(target, invert) {
var toShow = this,
hasContents = function(target) {
return $(target).val().trim().length
|| $(target).html().trim().length;
},
shouldHide = function(target) {
return invert ? hasContents(target) : !hasContents(target);
},
watch = function() {
if (shouldHide(target)) {
toShow.slideUp();
} else {
toShow.slideDown();
}
};
var type = $(target).attr('type');
if (type === 'radio' || type === 'checkbox') {
hasContents = function() {
return $(target)[0].checked;
};
}
if (type === 'radio') {
// Do not watch the radio button alone, watch for all in same group
$('[name="' + $(target).attr('name') + '"]')
.click(watch)
.keyup(watch)
.change(watch);
} else {
$(target)
.change(watch)
.keyup(watch)
.click(watch)
.focusout(watch);
}
//initial status
if (shouldHide(target)) {
$(toShow).hide();
} else {
$(toShow).show();
}
return this;
};
$(document).ready(function() {
$('.showwhenBI').showWhen($('[name="BI"]'));
});