Reputation: 851
I would like to make add / remove a class to a div that holds a checkbox.
I am 80% there, though am not sure on the right syntax to look at whether the input item is checked or unchecked. So I can add or remove the class appropriate.
Essentially I know it needs to look like:
if("$thechecks #item-" + req).attr('checked') {
$("#item-" + req).addClass("item-select");
} else {
$("#item-" + req).removeClass("item-select");
}
Any help / thoughts would be really appreciated.
I made a small fiddle of my code to-date.
http://jsfiddle.net/brandrally/vc5wgpk2/
// Javascript //
$(document).ready(function () {
$("#thechecks input[type='checkbox']").click(function () {
var req = $(this).val();
$("#item-" + req).addClass("item-select");
});
});
// HTML //
<div id="thechecks">
<div id="item-1">
<label><input name="element[]" type="checkbox" value="1" > One</label>
</div>
<div id="item-2">
<label><input name="element[]" type="checkbox" value="2" > Two </label>
</div>
</div>
Upvotes: 0
Views: 3816
Reputation: 6705
<ui>
<li><label><input id="checkbox2" type="checkbox" />Apple</label></li>
</ui>
//code before
<div id="wr" class="wrapper">
//code after
Add/remove class to the
<div id="wr" class="wrapper"> by checkbox
click:
<script>
$(document).ready(function(){
$('#checkbox2').click(function () {
$('#wr').toggleClass('on');
});
});
</script>
Upvotes: 0
Reputation: 2200
Try this one
$(document).ready(function () {
$("#thechecks input[type='checkbox']").click(function () {
var req = $(this).val();
if($("#item-"+req).hasClass("item-select"))
{
$("#item-" + req).removeClass("item-select");
} else {
$("#item-" + req).addClass("item-select");
}
});
});
Upvotes: 0
Reputation:
Try jquery closest
and toggleClass
:
$(function() {
$('input[name^=element]').on('change', function(e) {//input name starting with `element`
e.stopPropagation();
$(this).closest('div[id^=item]').toggleClass('check', this.checked);
}).trigger('change');//fire on page load
});
.check {
background: skyblue;
}
div[id^=item] {
margin-bottom: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thechecks">
<div id="item-1">
<label>
<input name="element[]" type="checkbox" value="1">One</label>
</div>
<div id="item-2">
<label>
<input name="element[]" type="checkbox" value="2" checked='checked'>Two</label>
</div>
</div>
Upvotes: 0
Reputation: 4637
Try this
Use toggleClass
instead of addClass
// $("#item-" + req).addClass("item-select");
$("#item-" + req).toggleClass("item-select");
Upvotes: 0