Home >Web Front-end >JS Tutorial >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!