Reputation: 209
Thank you in advance! New to Javascript.
I need to develop custom checkboxes that sit inside a div, and when you click the label or checkbox the div's border and font color change. Thought I could do this with CSS, but I'm starting to think I need JS.
Here's my code so far:
CSS:
input[type=checkbox] {
display: none;
}
div.label {
display:block;
border: 1px solid gray;
border-radius: 23px;
line-height: 30px;
height:50px;
width: 225px;
text-align:center;
}
label {
color:gray;
line-height:50px;
}
label:before {
content: "";
display: inline-block;
width: 13px;
height: 13px;
margin-right: 10px;
background-color: #ffffff;
}
input[type=checkbox]:checked + label:before {
content: "\2713";
font-size: 15px;
color: red;
line-height: 15px;
margin-left:10px;
margin-top: 15px;
}
input[type=checkbox]:checked + label:after {
color: red;
}
HTML:
<div class="label">
<input id="weekly" type="checkbox" name="lists[weekly]" value="True" />
<label for="weekly">Weekly Preview Email</label><br>
</div>
Any help is much appreciated!!
Upvotes: 2
Views: 6137
Reputation: 1121
Using jQuery,
$(function(){
$('input[type="checkbox"]').on('change', function(e){
return $(this).parent().toggleClass('checked');
});
});
This will add a "checked" class to the parent div. You can define CSS for the parent.
Working fiddle here.
EDIT: Based on the comment, added a style in CSS to color the label. Fiddle here.
Upvotes: 2
Reputation: 24692
It's possible with just CSS:
The checkbox needs to be directly before the first thing that you want to style. In your example it needs to be in front of div.label
. For multiple divs in a page make sure to change each for
and corresponding id
.
input:checked + div
will target only the div directly after an input that has been checked.
Have a jsBin example! (now with a tick)
Here is the same example with multiple checkboxes and divs
HTML
<input id="weekly" type="checkbox" name="lists[weekly]" value="True" />
<div class="label">
<label for="weekly">Weekly Preview Email (click me)</label><br>
</div>
CSS
input[type=checkbox] {
display: none;
}
input:checked + div {
border: solid 1px #000;
color: #F00;
}
input:checked + div:before {
content: "\2713";
padding: 20px;
}
Upvotes: 0
Reputation: 96
I would do something like
$('.label').click(function(){debugger;
$(this).toggleClass("checked")
});
Adding a checked css class
.checked {
border:1px solid black;
color:red;
}
It will do what you want, change the border/text on checking/unchecking the checkbox or clicking the label.
Upvotes: 0