简体   繁体   中英

Checkbox show/hide not working with jQuery

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>

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.

 $('#chkbx').change(function () {

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM