Categories
JavaScript Answers

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

Spread the love

Sometimes, we may want to get the value of a checked checkbox within our web app.

In this article, we’ll look at how to get the value of a checked checkbox with JavaScript.

Get All Checked Checkboxes

We can use plain JavaScript to get all the checked checkboxes.

For instance, if we have the following checkboxes:

<input type="checkbox" value="1" name="mailId[]" checked>1
<input type="checkbox" value="2" name="mailId[]" checked>2
<input type="checkbox" value="3" name="mailId[]">3

Then we can select all the checkboxes that are checked and get their values with:

const checked = document.querySelectorAll('input[type="checkbox"]:checked');
console.log([...checked].map(c => c.value))

We add the :checked pseudoselector to select all the checked checkboxes.

The first 2 checkboxes have the checked attribute, so we should get the value of the first 2 with it.

Then we log the value property.

We spread the checked NodeList into an array.

Then we call map with a callback to return the value property of each checkbox that is checked.

Therefore, the console log should log [“1”, “2”] .

Conclusion

We can get the value of all the checked checkboxes with plain JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *