Home  >  Article  >  Web Front-end  >  How Can I Retrieve the Value of a Selected Checkbox in JavaScript?

How Can I Retrieve the Value of a Selected Checkbox in JavaScript?

DDD
DDDOriginal
2024-10-21 17:26:02725browse

How Can I Retrieve the Value of a Selected Checkbox in JavaScript?

How to Retrieve the Value of a Selected Checkbox in JavaScript

When handling a group of checkboxes, it can be necessary to retrieve the value of the selected checkbox for further processing. In this article, we will explore how to accomplish this in JavaScript.

Let's consider the following HTML markup:

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

Using document.querySelector() for Singular Selection

Since the requirement specified that there will only be one checked checkbox, we can utilize the document.querySelector() method to select the checked checkbox.

<code class="javascript">document.querySelector('.messageCheckbox').checked; // true or false</code>

This code will return a boolean value (true if the checkbox is checked or false otherwise).

The above is the detailed content of How Can I Retrieve the Value of a Selected 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