HTML DOM Input Checkbox Object

HTMLWeb DevelopmentFront End Technology

The HTML DOM Input Checkbox Object represents an input HTML element with type checkbox.

Syntax

Following is the syntax −

  • Creating an <input> with type checkbox
var checkboxObject = document.createElement(“input”);
checkboxObject.type = “checkbox”;

Attributes

Here, “checkboxObject” can have the following attributes −

AttributesDescription
autofocusIt defines if the checkbox should be focused on initial page load.
checkedIt defines the state of checkbox i.e. checked/unchecked.
defaultCheckedIt returns the default value of checked attribute i.e. true/false
defaultValueIt sets/returns the default value of checkbox
disabledIt defines if checkbox is disabled/enabled
formIt returns a reference of enclosing form that contains the checkbox
indeterminateIt sets/returns indeterminate state of checkbox
nameIt defines the value of name attribute of a checkbox
requiredIt defines if the checkbox is compulsory to be checked in order to submit the form
typeIt returns the type of form element of checkbox
valueIt defines the value of the value attribute of a checkbox

Example

Let us see an example of Input Checkbox value property −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>Value Attribute of Checkbox</title>
</head>
<body>
<form id="Form">
<div>
Color-Red: <input value="Green" id="formCheckbox" type="checkbox" name="formCheckbox">
</div>
</form>
<button onclick="changeType()">Change value of input checkbox</button>
<div id="displayDiv"></div>
<script>
   var valueOfInput = document.getElementById("formCheckbox");
   var displayDiv = document.getElementById("displayDiv");
   displayDiv.textContent = 'Value: ' + valueOfInput.value;
   function changeType(){
      if(valueOfInput.value == 'Green' && valueOfInput.checked == true){
         valueOfInput.value = 'Red' displayDiv.textContent = 'value: ' + valueOfInput.value;
      } else {
         displayDiv.textContent = 'Check the checkbox to change value to red';
      }
   }
</script>
</body>
</html>

Output

This will produce the following output −

Before clicking ‘Change value of input checkbox’ button −

After clicking ‘Change value of input checkbox’ button −

Checked ‘Color-Red’ checkbox & clicking ‘Change value of input checkbox’ button −

raja
Published on 19-Jul-2019 11:45:22
Advertisements