Hi, how do I set a Form Element - Checkbox auto-checked through custom code? Any help is appreciated. Thanks!
To set a checkbox as auto-checked using JavaScript, you can use the .checked
property. Here’s an example:
JavaScript Code:
// Select the checkbox element by its ID, class, or any valid selector
const checkbox = document.querySelector('#yourCheckboxId');
// Set the checkbox to be checked
checkbox.checked = true;
// Optionally log or perform further actions
console.log('Checkbox is now auto-checked.');
Example HTML:
<form>
<label>
<input type="checkbox" id="yourCheckboxId">
I agree to the terms and conditions
</label>
</form>
Explanation:
-
document.querySelector('#yourCheckboxId')
: Finds the checkbox element. Replace#yourCheckboxId
with the actual ID, class, or selector for your checkbox. -
checkbox.checked = true;
: Sets thechecked
property totrue
, which checks the checkbox.
For Multiple Checkboxes:
If you need to auto-check multiple checkboxes:
const checkboxes = document.querySelectorAll('.yourCheckboxClass');
checkboxes.forEach(checkbox => {
checkbox.checked = true;
});
This will check all checkboxes that match the .yourCheckboxClass
selector. Let me know if you need further assistance!