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>
To obtain the value of the currently checked checkbox using JavaScript, employ the following method:
<code class="javascript">document.querySelector('.messageCheckbox').checked;</code>
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!