Home > Web Front-end > JS Tutorial > body text

How to Get the Value of a Checked Checkbox in JavaScript?

Mary-Kate Olsen
Release: 2024-10-21 17:06:02
Original
313 people have browsed it

How to Get the Value of a Checked Checkbox in JavaScript?

Getting the Value of a Checked Checkbox in JavaScript

In web development, obtaining the value of a checked checkbox is a common task. Given a set of checkboxes, the objective is to retrieve the value associated with the currently checked checkbox.

SOLUTION

To extract the value of the checked checkbox, we can utilize the property .checked of the querySelector function. Here's the syntax:

<code class="javascript">document.querySelector('.messageCheckbox').checked;</code>
Copy after login

This line of code retrieves the first element that matches the messageCheckbox class and returns the checked property. If the checkbox is checked, it returns true; otherwise, it returns false.

EXAMPLE

Consider the following HTML fragment:

<code class="html"><input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]"></code>
Copy after login

In this example, executing the JavaScript code will provide the value of the checked checkbox. If the first checkbox is checked, it will return "3". If the second checkbox is checked, it will return "1".

The above is the detailed content of How to Get the Value of a Checked Checkbox in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!