Using jQuery you can determine if a checkbox has been checked, performing an action based on the result. For example, you may want to conditionally show or hide form fields when a checkbox is selected.
The best way to do this is to use is to use is(":checked")
. This combines the is()
method with the :checked
selector, effectively checking whether a passed jQuery object is checked or selected, returning true
or false
.
if ( $('input[name="subscribe"]').is(':checked') ) {
$('input[name="email"]').show();
}
else {
$('input[name="email"]').hide();
}
To take this a step further, you can use this logic within a click
event callback function to perform an action when a checkbox is checked or unchecked.
$('input[name="subscribe"]').on('click', function(){
if ( $(this).is(':checked') ) {
$('input[name="email"]').show();
}
else {
$('input[name="email"]').hide();
}
});
For a more relevant example, here’s a working demonstration.
JavaScript
var $conditionalInput = $('input.conditionally-loaded');
var $subscribeInput = $('input[name="subscribe"]');
$conditionalInput.hide();
$subscribeInput.on('click', function(){
if ( $(this).is(':checked') )
$conditionalInput.show();
else
$conditionalInput.hide();
});
CSS
input.conditionally-loaded {
padding: 6px 8px;
min-width: 200px;
border-radius: 4px;
border: 1px solid #ccc;
}
input[name="subscriber"] {
margin-left: 10px;
}
HTML
<form>
<p>Do you want to subscribe? <input type="checkbox" name="subscribe" /></p>
<p><input type="email" placeholder="[email protected]" class="conditionally-loaded" /></p>
</form>