1

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>

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I put the remove so no data is passed when empty or disabled and hidden.. when it unchecked
0
 $('#chkbx').change(function () {

   $('.email').toggle();
 });

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.