css / jquery - checked issue
by porzechowski
HTML
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<span class="add-to-bookmark add-btn">
<input class="add-to-favorites-checkbox js_bookmark-check" type="checkbox" id="checkbox1" value="1" name="checkbox-favorites">
<label class="add-to-favorites-checkbox-icon" for="checkbox1"><span></span> Add to fav 1 </label>
</span>
<span class="add-to-bookmark add-btn">
<input class="add-to-favorites-checkbox js_bookmark-check" type="checkbox" id="checkbox2" value="2" name="checkbox-favorites">
<label class="add-to-favorites-checkbox-icon" for="checkbox2"><span></span> Add to fav 2 </label>
</span>
CSS
.add-to-favorites-checkbox[type="checkbox"] + .add-to-favorites-checkbox-icon span {
width: 16px;
height: 16px;
background-color: red;
display: block;
}
.add-to-favorites-checkbox[type="checkbox"]:checked + .add-to-favorites-checkbox-icon span {
background-color: green;
display: block;
}
input {
display: none;
}
JavaScript
$(document).ready(function() {
/**
/* for first checkox we can see changed color, after checkox status is changed
/* for second checkbox attribute checked and prop is changed, but CSS is not recognizing it
**/
// this is code for checkbox 1 - working
$('body').on('change', '#checkbox1', function (e) {
e.preventDefault();
if ($(this).attr('checked')) {
console.log("checkbox1 status: "+$(this).attr('checked')+"=>"+$(this).prop('checked'));
return;
}
console.log("checkbox1 status: "+$(this).attr('checked')+"=>"+$(this).prop('checked'));
});
// this is code for checkbox 2 - css not working
$('body').on('click', '#checkbox2', function (e) {
e.preventDefault();
if ($(this).attr('checked')) {
$(this).removeAttr('checked');
$(this).prop( "checked",false );
console.log("checkbox2 status: "+$(this).attr('checked')+"=>"+$(this).prop('checked'));
return;
}
$(this).attr('checked','checked');
$(this).prop( "checked",true )
console.log("checkbox2 status: "+$(this).attr('checked')+"=>"+$(this).prop('checked'));
});
});