admin管理员组文章数量:1309921
I am new to jQuery. I am trying to make a switcher using a checkbox. At the moment I have gone this far
$(function() {
$('input.cbx').on('change', function() {
if ($(this).prop("checked", true)) {
$('body').addClass('dark');
} else if ($(this).prop("checked", false)) {
$('.body').addClass('light');
}
});
});
<script src=".1.1/jquery.min.js"></script>
<input id="dn" type="checkbox" class="cbx hidden" />
<label for="dn" class="lbl"></label>
I am new to jQuery. I am trying to make a switcher using a checkbox. At the moment I have gone this far
$(function() {
$('input.cbx').on('change', function() {
if ($(this).prop("checked", true)) {
$('body').addClass('dark');
} else if ($(this).prop("checked", false)) {
$('.body').addClass('light');
}
});
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dn" type="checkbox" class="cbx hidden" />
<label for="dn" class="lbl"></label>
As you can see the checkbox stay checked after the first click, I imagine is a noob situation but, can you help me please?
Share Improve this question edited Sep 21, 2015 at 11:39 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Sep 21, 2015 at 11:24 Nicola BertelloniNicola Bertelloni 3331 gold badge3 silver badges17 bronze badges2 Answers
Reset to default 6You are actually setting the checked property instead of getting.
$('input.cbx').on('change', function() {
if($(this).prop("checked") == "true")
{
$('body').addClass('dark');
} else if($(this).prop("checked") == "false")
{
$('.body').addClass('light');
}
});
You can use this.checked
or $(this).is(":checked")
instead of $(this).prop("checked")
$('input.cbx').on('change', function() {
if(this.checked)
$('body').addClass('dark');
else
$('.body').addClass('light');
});
You can also use toggleClass
$('input.cbx').on('change', function() {
$('.body').toggleClass('light');
});
Note: I could not see any element with class body? You probably need to assign class to label. If you want to apply the toggle effect to body then remove dot
Live Demo
HTML
<body class="cbx">
<input id="dn" type="checkbox" class="cbx hidden"/>
<label for="dn" class="lbl">123</label>
</body>
Javascript
$('input.cbx').on('change', function() {
$('body').toggleClass('light');
});
$('input.cbx').on('change', function () {
if ($(this).is(":checked")) {
alert('checked');
} else {
alert('not checked');
}
});
DEMO
You can check if the checkbox is check using $(this).is(":checked")
本文标签: javascriptTrigger checkbox change class in JqueryStack Overflow
版权声明:本文标题:javascript - Trigger checkbox change class in Jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741820972a2399361.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论