admin管理员组文章数量:1201410
I'm trying to see if a checkbox is checked or not with a simple function. It doesn't seem to be working, here's the code:
HTML:
<form>
<input type="checkbox" id="check" />
</form>
JS:
$(document).ready(function() {
if ($('#check').is(":checked")) {
alert('it works')
}
});
JSFiddle: /
I'm trying to see if a checkbox is checked or not with a simple function. It doesn't seem to be working, here's the code:
HTML:
<form>
<input type="checkbox" id="check" />
</form>
JS:
$(document).ready(function() {
if ($('#check').is(":checked")) {
alert('it works')
}
});
JSFiddle: https://jsfiddle.net/5h58mx1h/
Share Improve this question asked May 18, 2016 at 13:47 Lxs29Lxs29 1751 gold badge2 silver badges14 bronze badges 3- 2 First you need to add checked attribute and then try..it will alert 'it works' => try jsfiddle.net/8vf3uLef – Dhara Parmar Commented May 18, 2016 at 13:48
- this works, if you want to get a message, when checked is changed, go for the changed event. – Nils Commented May 18, 2016 at 13:49
- It's working fine - your check box is not checked, so you don't get the alert. – fdomn-m Commented May 18, 2016 at 14:09
5 Answers
Reset to default 9Your code only runs once - when document
is ready. You need to attach an event listener to the checkbox and check when it changes:
$(document).ready(function() {
$('#check').change(function() {
if ($(this).is(":checked")) {
alert('it works');
}
});
});
Fiddle
You don't need jQuery. An <input type="checkbox">
has a checked
attribute, which you can use like this:
document.addEventListener("DOMContentLoaded", () => {
if (document.getElementById("check").checked) {
alert('it works')
}
})
It should be work:
$(document).ready(function () {
var ckbox = $('#checkbox');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
jsFiddle
I think this is the most simple way:
if ($('#check').checked) {
alert('it works');
}
Replace your HTML
to this
<form>
<input type="checkbox" id="check" checked />
</form>
This will work for you. Because you don't checked checkbox yet that's why not alert.
本文标签: How to get bool value from checkbox in javascriptjqueryStack Overflow
版权声明:本文标题:How to get bool value from checkbox in javascriptjquery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738605100a2102296.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论