I am building a mobile web app with jQuery Mobile and I want to check if a checkbox is checked. Here is my code.
This should work
function validate() {
if ($('#remeber').is(':checked')) {
alert("checked");
} else {
alert("You didn't check it! Let me check it for you.");
}
}
checked
is boolean
property so you can directly use it in IF
condition:-
<script type="text/javascript">
function validate() {
if (document.getElementById('remember').checked) {
alert("checked");
} else {
alert("You didn't check it! Let me check it for you.");
}
}
</script>
Use this below simple code: https://jsfiddle.net/Divyesh_Patel/v7a4h3kr/7/
<input type="checkbox" id="check">
<a href="#" onclick="check()">click</a>
<button onclick="check()">button</button>
<script>
function check() {
if (document.getElementById('check').checked) {
alert("checked");
} else {
alert("Not checked.");
}
}
</script>
You can also use JQuery methods to accomplish this:
<script type="text/javascript">
if ($('#remember')[0].checked)
{
alert("checked");
}
</script>
I am using this and it works for me with Jquery:
Jquery:
var checkbox = $('[name="remember"]');
if (checkbox.is(':checked'))
{
console.log('The checkbox is checked');
}else
{
console.log('The checkbox is not checked');
}
Is very simple, but work's.
Regards!
Try This
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
if (input.checked) {
alert("checked");
} else {
alert("You didn't check it.");
}
}
input.onchange = check;
check();
}
</script>