Subject: Re: Form field validation - verify checkbox using JavaScript
Author: WebSpider
In response to: Form field validation - verify checkbox using JavaScript
Posted on: 06/27/2011 06:02:27 PM
The corresponding HTML should be as follows.
<html>
<body>
<form onsubmit="return verify_checkbox(this.checkbox);" action="">
<input type="checkbox" id="checkbox" value="Dog">Dog</p>
<input type="checkbox" id="checkbox" value="Cat">Cat</p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
>
> On 08/01/2006 09:58:56 PM
WebSpider wrote:
It is very common to see if a checkbox has been checked or not before a form being sent out to server. This can be done by the following javascript code
<script language="JavaScript">
function verify_checkbox(checkbox)
{
var isChecked = false;
if checkbox[0]) { /* chackbox group/array */
for(var j=0; j<checkbox.length; j++){
if(checkbox[j].checked){
alert("The checkbox #"+(j+1)+"has been checked.");
isChecked = true;
}
}
}else{
if(checkbox.checked){
alert("The checkbox has been checked.");
isChecked = true;
}
}
if(!isChecked)
alert("No checkbox has been checked.");
}
</script>
What we have learned are:
The attribute 'checked' of checkbox plays a key role;
There could be an array of checkboxes bearing the same group name.
References: