HTML DOM Input Checkbox required Property
Last Updated :
30 Jan, 2024
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:Â
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.
html
<!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 >
< 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 >
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.
html
<!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)" >
< input type = "checkbox"
name = "check"
id = "GFG"
value = "1"
required>
Checked by default< br >
< br >
< button type = "submit" >
Submit
</ button >
</ form > < br >
< 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
Supported Browsers:
- Google Chrome 1
- Edge 12
- Firefox 1
- Opera 15
- Safari 1
Share your thoughts in the comments
Please Login to comment...