Home  >  Article  >  Web Front-end  >  How to Get the Value of a Checked Checkbox in JavaScript?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 17:06:02318browse

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>

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>

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!

Statement:
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