Get checked checkbox values only from HTML form with JavaScript
Last updated: December 13, 2022.
Getting checked checkbox values from a form requires a little more programming than simply getting form values using the FormData(form) approach. This standard approach would return all checkbox values with a value of either true or false for each.
The approach we use below will store the values of checked checkboxes only in an array that can then be stored as a property value on a JavaScript object or in an array of arrays (entries).
Below is the HTML form we’ll be using in this example. For realism, other inputs exist on the form:
<form>
<div class="names">
First name<br>
<input type="text" name="first-name"><br>
Last name<br>
<input type="text" name="last-name"><br>
</div>
<div class="skills">
<input type="checkbox" value="HTML">HTML<br>
<input type="checkbox" value="CSS">CSS<br>
<input type="checkbox" value="JavaScript">JavaScript<br>
</div>
<button type="submit">Submit</button>
</form>
The solution below is to push only those checkbox values that a user has selected into a new array and then append this to a FormData
object.
Because the data on a FormData
object is stored in array-like format, it can be converted to a proper array with Array.from()
or a JavaScript object using Object.fromEntries()
:
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
// Prevents HTML submission and page refresh
const fd = new FormData(form);
// Attaches all elements in form with name attribute to new FormData object
let skills = [];
// Creates array into which skills will be pushed if checked
document.querySelectorAll('[type="checkbox"]').forEach(item => {
// Iterates through all checkbox elements
if (item.checked === true) {
skills.push(item.value);
// Pushes checkbox value into skills array if checked
}
})
fd.append('skills', JSON.stringify(skills));
// Stringify array to JSON and append to FormData object
console.log(Object.fromEntries(fd));
// Prints result as object
console.log(Array.from(fd));
// Prints result as array
});
Don't forget to include the name
attribute on the other form inputs! Otherwise, they won't be appended to the formData
when calling new FormData(form)
.
Related posts
- Save user form input data in a JavaScript object
- POST form data using JavaScript’s Fetch API
- Using JSON in JavaScript