I've a check-box inside div.
<div id="question_text_1">
<input type="checkbox" onChange="myFunction(question_text_1)">Sample question text
</div>
I'm trying to toggle the background color of div
whenever checkbox is checked or unchecked, which is not working.
Here is the complete code
However, implementing same code without toggle logic is working fine - link
Kindly suggest what could be going wrong.
The problem is that
x.style.backgroundColor
will return color's value only if it is set as inline style. And it will return rgb, not hex. You should better make the verification based onchecked
attribute of the checkbox:http://codepen.io/anon/pen/avLrze
Instead of x.style.backgroundColor in if condition use window.getComputedStyle(x).backgroundColor and compare with 'rgb' equivalent of colors.
Hope this helps.
Thanks
The code doesn't work because
x.style.backgroundColor
always returns''
- empty string andelse
block is executed.To get the values see How to get an HTML element's style values in javascript?
You can achieve this using CSS, no need of using Javascript
label
element:checked
property of the checkbox to apply styles when the checkbox is checked+
), on checked checkbox to set styles on the labelIf you want to use Javascript, use
classList
!important
to override styles in the class as the id selector have higher specificityclassList.toggle
to toggle classUpdated Pen
You can try it with jQuery like this:
HTML
jQuery
Checkout the jsfiddle.
please change you code like below,It works fine
You can not directly compare div background color with value of color because for it you must have to declare variable of color related to different browser for that visit this link How to compare a backgroundColor in Javascript?