Basics of HTML form checkbox
Checkbox Object :
The following syntax will get the checkbox object in javascript
Syntax: document.formname.checkboxname
Example Code:
<form name=testform>
<input name=cb1 value=test type=checkbox>
<input name=cb2 value=test2 type=checkbox>
</form>
<script language="javascript">
var cbobject= document.testform.cb1;
</script>
The object cbobject is an array of check box element.
To use the first check box, we have to call cbobject[0], for second box it is
cbobject[1] and so on.. Here are the events, dom properties and method associated with
checkbox element.
Event Handlers: Associated with Form type Check Box:
All the examples below use a javascript function output
<script language=javascript>
function output()
{
alert("testing checkbox events");
}
</script>
DOM Properties:
The following are the list of DOM (Dynamic Object Model) properties
that can be used to get and alter checkbox properties in javascript.
The below examples are based on the form
<form name=testb>
<input name=mycb type=checkbox value=111> box1
<input name=mycb type=checkbox value=222> box2
</form>
| DOM Property | Description | Example |
| checked | Used to check or select checkbox.
Each element has to be checked individually. The element if selected will return true else false. |
To Check:
var ss = document.testb.mycb[0].checked;
var ss1 = document.testb.mycb[1].checked;
To Select:
document.testb.mycb[0].checked = true;
|
| defaultChecked | Used to check whether the check box is
selected by default |
To Get:
var ss = document.testb.mycb[0].defaultChecked;
|
| form | Used to get the parent node (form object)
of this check box |
To Get:
var ss = document.testb.mycb[0].form;
|
| name | Used to get checkbox name |
To Get:
var ss = document.testb.mycb[0].name;
|
| type | Used to get form type |
To Get:
var ss = document.testb.mycb[0].type;
|
| value | Used to set or get checkbox value |
To Get:
var ss = document.testb.mycb[0].value;
To Set::
document.testb.mycb[0].value = "testy";
|
DOM Methods:
The following are the list of DOM (Dynamic Object Model) methods
that can be used to do dynamic changes like dynamic check box selection, using javascript.
| DOM Method | Description | Example |
| click() | Used to dynamically make a checkbox checked |
To Click:
document.testb.mycb.click();
|
| blur() | Used to dynamically make the check box blur |
To Blur:
document.testb.mycb.blur();
|
| focus() | Used to dynamically get focus on the check box |
To Focus:
document.testb.mycb.focus();
|
Example: Making Check Box Select on Mouse Over
<script language=javascript>
function cbevent()
{
var xx = document.xx.cbtest;
xx.checked = true;
}
</script>
<form name=xx>
<input type=checkbox name=cbtest onMouseOver="cbevent()"> Checking
</form>
Result:
|