Reputation: 13448
I want to show an email field only if a checkbox is checked.
If the checkbox is not checked the email field must be hidden.
Here is my code:
$('#chkbx').click(function () {
var $this = $(this);
if ($this.is(':checked')) {
$('.email').hide();
$('.email').remove();
} else {
$('.email').show();
}
});
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<label class="checkbox-inline col-xs-10">
<input type="checkbox" ID="chkbx"> Email me the report when ready.
</label>
</div>
</div>
<div class="form-group email">
<div class="col-xs-offset-3 col-xs-8">
<div class="col-xs-8">
<input type="text" class="form-control " placeholder="Enter your email">
</div>
</div>
</div>
Upvotes: 1
Views: 397
Reputation: 4294
If you are able to change the HTML a little bit, you could easily do it with CSS-only.
You can use the ~
operator to select the next input
that comes after the input[type=checkbox]:checked
:
.form-group input.form-control {
display: none;
}
.form-group input[type=checkbox]:checked ~ input.form-control {
display: block;
}
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<input type="checkbox" ID="chkbx">
<label for="chkbx" class="checkbox-inline col-xs-10">Email me the report when ready.</label>
<input type="text" class="form-control" placeholder="Enter your email">
</div>
</div>
Upvotes: 0
Reputation: 76557
Have you considered using the toggle()
function, which is designed to handle this type of behavior?
$('#chkbx').click(function () {
// This will show / hide your element accordingly
$('.email').toggle();
});
You can also pass in a given condition to the function to determine if it should be shown or not :
// Show or hide depending on the state of your current checkbox element
$('.email').toggle(this.checked);
Additionally, you don't likely want to call the remove()
function, as that will entirely remove it from the DOM, rendering it unable to be accessed in the future.
Upvotes: 3