Mar
22
JavaScript - Get Form Checkbox Array Values
March 22, 2008 |
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
- JavaScript Convert CSV to Array
- JavaScript Control Flash Replay
- JavaScript - Unobtrusive Slideshow
- JavaScript - Ways to Create Markup
- Prototype Drop Down Menu
- JavaScript - Remove the Last Character of a String
- Prototype Function Variable inside Observe
- JavaScript Stop a Loop
- Mootools Prevent Ajax Request Cache
Comments
1 Comment so far



































Simple & Perfect! Thank you :)