Skip to content

Instantly share code, notes, and snippets.

@dgpro
Created January 31, 2019 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgpro/66e737c1f2f4b2cad1891a1e3c597f57 to your computer and use it in GitHub Desktop.
Save dgpro/66e737c1f2f4b2cad1891a1e3c597f57 to your computer and use it in GitHub Desktop.
jQuery Checkbox Toggle Show/Hide Elements
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function () {
// Show and hide filter block based on selected checkbox toggle-source
function toggleFilters(name, delay) {
delay = delay || 0;
if ($('input[name=' + name + ']').is(':checked')) {
$('.hide-when-' + name).fadeOut(delay)
$('.show-when-' + name).delay(delay).fadeIn(delay)
} else {
$('.show-when-' + name).fadeOut(delay)
$('.hide-when-' + name).delay(delay).fadeIn(delay)
}
}
$('input[type=checkbox].toggle-source').each(function () {
toggleFilters($(this).attr('name'), 700)
})
$('input[type=checkbox].toggle-source').change(function () {
toggleFilters($(this).attr('name'), 700)
})
})
</script>
<form>
<div>
<label><input type="checkbox" class="toggle-source" name="test"> Hide One and Show Another</label>
</div>
<div class="hide-when-test">I'm the One</div>
<div class="show-when-test"> I'm Another</div>
</form>
<a href="https://codepen.io/dgpro/pen/rPjRzm" target="_blank">Demo</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment