Suppose you have a web page with a checkbox like a registration page where you have a checkbox about reading terms and conditions. When the user clicks the submit button, your job is to validate whether that particular checkbox is checked or not? How do you do that? How do you get the value of the checkbox to see if it's checked or not? Well, you can use a pseudo-selector ":checked" to see if that checkbox is checked or not. This selector returns true if the user has clicked and kept the checkbox checked; false otherwise. You can get the checkbox either by class or id and then you can call the is(":checked") method, as shown in our example.
How to find if the checkbox is checked using jQuery?
You can use the following jQuery code to check if the check-box is checked or not. It's literary a two-line code, and you can see for yourself:
$("#terms").is(":checked")
Will return true if the checkbox is checked and false if unchecked. In this line, we first get the checkbox reference by id, which is equivalent to getElementById(), and then calling is() method with ":checked" pseudo-selector.
Let's see a simple HTML/JSP example to see the code in action:
<html> <head> <title>How to get value from a checkbox in jQuery</title> </head> <body> <h2>How do you get the value of a checkbox using jQueryy</h2> <form id="register"> Enter your name : <input id="myTextbox" type="text" /><br /> Select gender : male <input type="radio" class="gender" name="gender" /> female <input type="radio" class="gender" name="gender" /><br /> Agreed to terms : <input id="terms" type="checkbox"><br /> <input id="submit" type="submit"><br> </form> <script src="//code.jquery.com/jquery-1.6.2.min.js"></script> <script> $(document).ready(function () { $("#submit").click(function () { alert($("#terms").is(":checked")); }); }); </script> </body> </html>
When you run the above HTML/JSP and click on the submit button, it will display true in the alert popup if the checkbox is checked or false otherwise.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.