Your code is fine. This is most likely not working on load because you haven't wrapped the code in a "ready" function. To then change the background colour of the checkboxes that are checked, you need to chain the css onto your query.
// this wrapper waits until the DOM has loaded before executing the code inside
$(function() {
$("input[type=checkbox]:checked").css('background-color', 'red')
})
If you were expecting the background colour to change as you toggle the checkboxes, you'll need to set up an event as well.
// this wrapper waits until the DOM has loaded before executing the code inside
$(function() {
var checkboxes = $("input[type=checkbox]")
// set the styles based on the initial state on load
checkboxes.is(':checked').css('background-color', 'red')
// update the styles as the checkbox states are changed
checkboxes.on('change', function() {
var checkbox = $(this)
checkbox.css('background-color', checkbox.is(':checked') ? 'red' : 'transparent'))
})
})
input[type='checkbox'] {
-webkit-appearance: none; /* necessary to override checkbox styles on OSX and iOS */
width: 20px;
height: 20px;
background: grey;
}
input[type='checkbox']:checked {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
NOTE: Checkboxes and radios have hard coded styles in many browsers on iOS and OSX. In order to explicitly override this, you need to use the appearance: none
(in this case -webkit-appearance
for Chrome and Safari) to allow your styles to override the browser defaults.