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!