Jamie Collingwood Jamie Collingwood - 1 month ago 11
CSS Question

Bootstrap checkboxes and jquery

I am using bootstrap check boxes which don't seem to behave the same way as normal check boxes. Looking on other posts, it seems bootstrap check boxes return a value of undefined so using a if checked does not work.

Code:

<div class="checkbox checkbox-primary">
<input id="homeaddress" type="checkbox" checked>
<label for="homeaddress">
Same As My Home Address
</label>
</div>
<div id="show-hide-address">
content
</div>



$("#show-hide-address").hide();
$(document).ready( function(){
$("#homeaddress").on("click", function(){
if ($(this).attr("checked")==undefined) {
$('#show-hide-address').slideUp(); // checked
} else {
$('#show-hide-address').slideDown(); // unchecked
}
});
});


When the page loads the checkbox is checked and the content div is invisible as it should be. When I un-check it, the content div does slide down as it should. BUT when I click the checkbox again, the slide up does not work, nothing happens. Has anyone dealt with this before. Am I missing something? Thanks,

UPDATE: added a fiddle
https://jsfiddle.net/gj3w046f/1/

Answer

Try this one:

$('#homeaddress').change(function() {
  if ($(this).is(':checked')) {
     $('#show-hide-address').slideUp();
  } else {
    $('#show-hide-address').slideDown();
  }
});

here is Fiddle