In this post, we will learn how to check a checkbox is checked or not using jQuery. So how we can do this, we will learn in this post.


How To Check A Checkbox Is Checked Or Not Using jQuery ?


Check A Checkbox Is Checked Or Not 

To check a checkbox is checked or not, we can use  prop()  method and  :checked  selector. With the help of both these methods, we can find out whether the checkbox is checked or unchecked. 


jQuery  prop()  Method

This method is an efficient way to find out the current status of radio buttons and checkboxes. So how we can use it, we will see it in the example below.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Check A Checkbox Is Checked Or Not Using jQuery ?</title>
</head>
<body>

<input id="checkBox" type="checkbox" name="language" value="jQuery">
<label for="language"> I am learning jQuery.</label>

<br><br><br>

<button>Check Status</button>

<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>


<script>
$(document).ready(function(){
$('button').click(function(){
if($('#checkBox').prop("checked") == true){
alert("Checkbox is checked.");
}
else if($('#checkBox').prop("checked") == false){
alert("Checkbox is unchecked.");
}
});
});

</script>
</body>
</html> code-box


This above code will also worked for radio buttons. You try it yourself.


jQuery  :checked  Selector

We can also use  :checked  selector  to find out the current status of radio buttons and checkboxes. So how we can use it, we will see it in the example below.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Check A Checkbox Is Checked Or Not Using jQuery ?</title>
</head>
<body>

<input id="radioButton" type="radio" name="language" value="jQuery">
<label for="language"> I am learning jQuery.</label>

<br><br><br>

<button>Check Status</button>


<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>


<script>
$(document).ready(function(){
$('button').click(function(){
if($('#radioButton').is(":checked")){
alert("Radio button is checked.");
}
else if($(this).is(":not(:checked)")){
alert("Radio button is unchecked.");
}
});
});

</script>
</body>
</html> code-box



Summary

In this post we learned how to check a checkbox is checked or not using jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts. 

Post a Comment

Previous Post Next Post