Mar

22

When you create a form with checkbox, you may expect people to check on more than one checkboxes, and you may ask: Can I get the group of user checked values? The answer is yes. Checkboxes can be used as arrays and the values can be collected using JavaScript.

Imagine you have the form below:


<form name="form1" onsubmit="return validate(this)">
<input type="checkbox" name="names" value="Tom">Tom
<input type="checkbox" name="names" value="Jef">Jef
<input type="checkbox" name="names" value='Kate'>Kate
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>

You want to get the list of names user checked, this can be done by using the following script:

function validate(form) {
var namelist = "";
with(document.form1) {
for(var i = 0; i < names.length; i++){
if(names[i].checked) {
namelist += names[i].value + "\n";
}
}
}
if(namelist == "") {
alert("select names");
} else {
alert (namelist);
}
return false;
}

A live example can be viewed at: JavaScript Checkbox Array demo



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

1 Comment so far

  1. Pavel on January 4, 2009 11:57 am

    Simple & Perfect! Thank you :)

Sponsors




Links