I want some elements to have a class applied to them if a checkbox is checked, and to have the class removed if they are not checked (or un-checked). I've tried writing this a few different ways but I'm only ever able to give apply the class to the elements once the checkbox is clicked, but re-clicking doesn't remove the class from the elements even though I expect it would.
jQuery(document).ready(function($) {
$('input[type="checkbox"]').on("click", function() {
if($('#filter-Acting').prop('checked') == true) {
$('.filter-item.Acting').addClass("hidden");
} else if ($('#filter-Acting').prop('checked') == false) {
$('.filter-item.Acting').removeClass("hidden");
}
}
});
What's the easiest way to accomplish what I'm after? Thanks.
*EDIT: None of the provided examples have worked for me so here is relevant markup for the form and a form item...
<form>
<fieldset>
<div class="row">
<div class="col-sm-12">
<div class="checkbox" id="check-Acting">
<input type="checkbox" id="filter-Acting" name="Acting" value="1" class="form-checkbox"/>
<label for="filter-Acting" data-toggle="tooltip" data-placement="top"><span>Acting</span></label>
</div>
</div>
</div>
</fieldset>
</form>
<div class="container">
<div class="panel filter-item Acting">
--
</div>
</div>
Without your html I may only assume it and propose you to use:
.toggleClass( className, state ) : one or more class to be toggled according to the state value
$('input[type="checkbox"]').on("change", function (e) { $('.filter-Acting').toggleClass("hidden", !$('#filter-item.Acting').is(':checked')); });
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="...."> <input type="checkbox" name="vehicle" value="Bike" id="filter-item" class="Acting"> Click me<br> <input type="text" class="filter-Acting hidden"><br> <input type="submit" value="Submit"> </form>
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.