Issue
I want to use images to create a custom checkbox. I know how to do this, and there are a lot of great alternatives on this site. But my number one goal here is learning so I would like to ask this question.
When I hide the HTML checkbox with CSS using display: none; the jquery code doesn’t work anymore. And that makes sense to me, but how can I make it so the custom checkbox with the images also functions like the original one?
HTML
<div id="togglecontainer">
<input type="checkbox" id="checkbox'+(counter)+'"class="item"/>
<label for="checkbox"></label>
<input value="make me bold" type="text" class="inputfield"/>
</div>
CSS
.inputfield{
padding-left: 20px;
}
label:before {
content: url("https://cdn1.iconfinder.com/data/icons/windows8_icons_iconpharm/26/unchecked_checkbox.png");
position: absolute;
z-index: 100;
}
input[type=checkbox]:checked+label:before {
content:url("https://cdn1.iconfinder.com/data/icons/windows8_icons_iconpharm/26/checked_checkbox.png");
}
input[type=checkbox] {
//display: none;
}
.complete {
font-weight: bold;
}
input[type=text] {
background-color:transparent;
border: 0px solid;
margin-left: 20px;
color:#222222;
font-size: 13px;
}
jQuery
$("#togglecontainer").delegate("input[type=checkbox]", "change", function () {
$(this).nextAll().toggleClass("complete");
});
P.s. A little side question; as you can see this fiddle uses an older version of jQuery. When I link to a newer version the whole thing doesn’t work anymore. Can someone elaborate on that a little as well?
Thanks in advance.
Solution
You can always wrap the checkbox inside the label and then not need the id
or the for
.
My example does not use images. I don’t need id
or for
and if you click on the text it also works.
I did make the text into just text and no longer an <input type="text">
field.
I also re-wrote the code in vanilla JS and not using jQuery. This will still work with jQuery in the rest of your code, bit it will also work without jQuery.
var el = document.querySelector("#togglecontainer");
el.addEventListener("change", evt => {
if (evt.target.type === "checkbox") {
evt.target.parentNode.classList.toggle("checked", evt.target.checked);
evt.preventDefault();
}
});
.my-checkbox:before {
content: '';
height: 20px;
display: inline-block;
border: 1px solid black;
border-radius: 3px;
vertical-align: middle;
width: 20px;
text-align: center;
}
.my-checkbox.checked {
font-weight: bold;
}
.my-checkbox.checked:before {
content: '✓';
}
.my-checkbox [type=checkbox] {
height: 0;
width: 0;
overflow: hidden;
position: absolute;
display: none;
}
<div id="togglecontainer">
<label class="my-checkbox">
<input type="checkbox"/>
make me bold
</label>
</div>
Answered By – Intervalia
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0