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











































#1 by Pavel on January 4, 2009 - 11:57 am
Simple & Perfect! Thank you :)
#2 by dima on November 6, 2009 - 12:36 am
Yes, I’m agree with first comment!
#3 by Admin on November 18, 2009 - 3:20 am
Check All Color
Red
Green
Blue
function checkout(check) {
var checkbox = document.frm_color.color;
if(check)
var chk = true;
else
var chk = false;
for(var i=0; i<checkbox.length; i++)
{
checkbox[i].checked=chk;
}
}
#4 by Admin on November 18, 2009 - 3:24 am
>br<
#5 by Admin on November 18, 2009 - 3:29 am
<form name=”frm_color”>
<br><input type=”checkbox” id=”main_chk” onclick=”checkout(this.checked)” /> Check All Color
<br>
<br> <input type=”checkbox” name=”color” value=”red” /> Red
<br> <input type=”checkbox” name=”color” value=”green” /> Green
<br> <input type=”checkbox” name=”color” value=”blue” /> Blue
</form>
<script>
function checkout(check) {
var checkbox = document.frm_color.color;
if(check)
var chk = true;
else
var chk = false;
for(var i=0; i<checkbox.length; i++)
{
checkbox[i].checked=chk;
}
}
</script>