The Input Checkbox required property in HTML DOM is used to set or return whether the input checkbox field should be checked or not before submitting the form. This property is used to reflect the HTML-required attribute.
Syntax:
- It returns the Input Checkbox required property.
checkboxObject.required
- It is used to set the Input Checkbox required property.
checkboxObject.required = true|false
Property Values:
Property Value |
Description |
---|---|
true |
It is used to specify the checkbox must be checked before submitting the form. |
false |
It has a default value. It specifies that the checkbox must not be checked before submitting the form. |
Return Value:
It returns a Boolean value which represents the checkbox must be checked or not before submitting the form.
Example 1: This example show what value is returned by the Input Checkbox required property.
<!DOCTYPE html> < html >
< head >
< title >
DOM Input Checkbox required Property
</ title >
< style >
body {
text-align: center;
}
h1 {
color: green;
}
</ style >
</ head >
< body >
< h1 >GeeksforGeeks</ h1 >
< h2 >DOM Input Checkbox required Property</ h2 >
< form >
<!-- Below input elements have attribute "required" -->
< input type = "checkbox"
name = "check"
id = "GFG"
value = "1"
required>
Checked by default< br >
< input type = "checkbox"
name = "check"
value = "2" >
Not checked by default< br >
</ form > < br >
< button onclick = "checkRequired()" >
Submit
</ button >
< p id = "sudo"
style = "color:green;font-size:20px;" ></ p >
<!-- Script to use required property -->
< script >
function checkRequired() {
let isRequired =
document.getElementById("GFG").required;
document.getElementById("sudo").innerHTML = isRequired
? "Checkbox is required."
: "Checkbox is not required.";
}
</ script >
</ body >
</ html >
|
Output:
Example 2: This example sets the Input Checkbox required property.
<!DOCTYPE html> < html >
< head >
< title >
HTML DOM Input Checkbox required Property
</ title >
< style >
body {
text-align: center;
}
h1 {
color: green;
}
</ style >
</ head >
< body >
< h1 >GeeksforGeeks</ h1 >
< h2 >HTML DOM Input Checkbox required Property</ h2 >
< form onsubmit = "return validateForm(e)" >
<!-- Single checkbox with attribute "required" -->
< input type = "checkbox"
name = "check"
id = "GFG"
value = "1"
required>
Checked by default< br >
< br >
< button type = "submit" >
Submit
</ button >
</ form > < br >
<!-- Script to validate and submit form -->
< script >
function validateForm() {
var checkbox = document.getElementById("GFG");
if (!checkbox.checked) {
// If checkbox is not checked, prevent form submission
document.getElementById("sudo").innerHTML =
"Checkbox is required!";
return false;
}
}
</ script >
</ body >
</ html >
|
Output:
HTML DOM Property
- HTML DOM Input Checkbox value Property
- HTML DOM Input Checkbox form Property
- HTML DOM Input Checkbox checked Property
Supported Browsers:
- Google Chrome 1
- Edge 12
- Firefox 1
- Opera 15
- Safari 1