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

How to Retrieve the Value of a Checked Checkbox Using JavaScript?

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

How to Retrieve the Value of a Checked Checkbox Using JavaScript?

Retrieving the Value of Checked Checkbox

In the realm of web development, it's often necessary to capture the value of an element, especially when working with form submissions. One common element that requires this functionality is a checkbox.

Suppose you have the following HTML code:

<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

To obtain the value of the currently checked checkbox using JavaScript, employ the following method:

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

This line of code uses the querySelector() method to select all elements with the class messageCheckbox. Since it's specified that there will be only one checked box, this line will return the first matching element.

The checked property of the selected checkbox is then checked, which will return either true if the box is selected or false if it's not. This allows you to easily determine the value associated with the checked checkbox.

The above is the detailed content of How to Retrieve the Value of a Checked Checkbox Using 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!