How to use FormData Object In Javascript
In this approach, we are using the FormData object to gather the checked status of checkboxes with the name âoptions[]â. By checking the length of the array of checked options, we determine if at least one option is selected, displaying an error message if not and listing the selected options otherwise.
Example: The below example uses FormData Object to validate the checkbox in JavaScript.
<!DOCTYPE html>
<html>
<head>
<style>
.error-message {
color: red;
}
</style>
</head>
<body>
<h1 style="color: green;">w3wiki</h1>
<h3>Approach 2: Using FormData Object</h3>
<form id="cbForm2">
<input
type="checkbox"
id="cb1"
name="options[]"
value="GFG">GFG<br>
<input
type="checkbox"
id="cb2"
name="options[]"
value="Google"> Google<br>
<input
type="checkbox"
id="cb3"
name="options[]"
value="Meta">Meta<br>
</form>
<button
type="button"
onclick="approach2Fn()">Validate</button>
<p
class="error-message"
id="errorMessage5"></p>
<p id="selectedOptions"></p>
<script>
function approach2Fn() {
const formData = new FormData(document
.getElementById('cbForm2'));
const checkedOptions = formData
.getAll('options[]');
if (checkedOptions.length === 0) {
document
.getElementById('errorMessage5')
.textContent = 'Please select at least one option.';
document
.getElementById('selectedOptions')
.textContent = '';
} else {
document
.getElementById('errorMessage5')
.textContent = '';
document
.getElementById('selectedOptions')
.textContent = 'Selected Options: ' + checkedOptions.join(', ');
}
}
</script>
</body>
</html>
Output:
How to Validate Checkbox in JavaScript?
Validation of checkboxes is important to make sure that users select the required options, enhancing data accuracy and user experience.
Table of Content
- Using a Loop
- Using FormData Object
Contact Us