JSFiddle - React, Tailwind, and code Playground
HTML
<ol class="questions">
<li>Do you smoke?
<ol>
<li><input type="radio" name="q1"/>Yes</li>
<li><input type="radio" name="q1"/>No <span data-skip-questions="2 3">(skip to 4.)</span></li>
</ol>
</li>
<li>How often do you smoke?
<ol>
<li><input type="radio" name="q2"/> Every hour</li>
<li><input type="radio" name="q2"/> Every two hours</li>
</ol>
</li>
<li>Do you realize ...
<ol>
<li><input type="radio" name="q3"/> Not really</li>
</ol>
</li>
<li>Is question four a question?
<ol>
<li><input type="radio" name="q4"/> Yes</li>
<li><input type="radio" name="q4"/> No</li>
</ol>
</li>
</ol>
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;
};
jQuery(function(){
$('span[data-skip-questions]').each(function() {
var questionsToSkip = $(this).data('skip-questions').split(' '),
q = $(null),
watchedInput = $(this).parents('li:first').find('input[type="radio"]');
$.each(questionsToSkip, function(i, val) {
q = q.add($('ol.questions > li')
.eq(val - 1));
});
$(q).hide().showWhen(watchedInput, true);
})
.hide();
});