Archive for JavaScript

JavaScript – Get Checkbox Value

Thursday, February 26th, 2009

Checkbox can be of two types, with same name and with different name. Same name checkbox is used for collection type i.e. id=1,2,3,4,5 .. n. The checkbox value can fetch with elements of form with same name. This checkbox has same nature so we define with it as same name.

document.frm.id1.value

With separate name checkbox value can get by property name. If we have a single checkbox in form, we can get value of checkbox by property name.

The example is showing how to get value of checkbox in JavaScript with elements of forms and single checkbox.

Demo

<html>
<head>
<title>JavaScript select checkbox</title>
<script>
function selectCheckBox()
{
  var e= document.frm.elements.length;
  var cnt=0;

  for(cnt=0;cnt<e;cnt++)
  {
    if(document.frm.elements[cnt].name=="id"){
     alert(document.frm.elements[cnt].value)
    }
  }
}
</script>
</head>

<body>
<form name="frm">
<input type="checkbox" name="id" value="1">
<input type="checkbox" name="id" value="2">
<input type="checkbox" name="id" value="3">
<input type="checkbox" name="id" value="4">
<input type="checkbox" name="id" value="5">
<input type="button" name="goto" onClick="selectCheckBox()" value="Check">
</form>
</body>
</html>

The example is showing how to get value from separate name checkbox in JavaScript.

<html>
<head>
<title>JavaScript select checkbox</title>
<script>
function selectCheckBox()
{
     alert(document.frm.id1.value)
     alert(document.frm.id2.value)
     alert(document.frm.id3.value)
}
</script>
</head>

<body>
<form name="frm">
<input type="checkbox" name="id1" value="1">
<input type="checkbox" name="id2" value="2">
<input type="checkbox" name="id3" value="3">

<input type="button" name="goto" onClick="selectCheckBox()" value="Check">
</form>
</body>
</html>