How to create a list of checkbox and retrieve selected checkbox value in javascript
+1
A:
To create an element in DOM, use document.createElement
. To retrieve selected checkbox value, use element.checked
and/or element.value
. To learn more about HTML DOM, start here.
You may want to consider using jQuery to ease all the DOM manipulation and traversing work.
BalusC
2010-04-27 12:24:46
+3
A:
Presuming a structure like:
<form name="test">
<input type="checkbox" name="colors" value="red'/>
<input type="checkbox" name="colors" value="orange'/>
<input type="checkbox" name="colors" value="yellow'/>
<input type="checkbox" name="colors" value="blue'/>
</form>
Then use something like this to retrieve the value:
var values = [];
var cbs = document.forms['test'].elements['colors'];
for(var i=0,cbLen=cbs.length;i<cbLen;i++){
if(cbs[i].checked){
values.push(cbs[i].value);
}
}
alert('You selected: ' + values.join(', '));
scunliffe
2010-04-27 12:28:10
`id` is preferred to `name` for identifying forms.
David Dorward
2010-04-27 12:31:40
@David (preferring id over name) is this just for simplicity? using the name attribute is fine, as is accessing by index if you know the position. If however I was to use the document.getElementById(id) function then I would surely use an id. Hmm, after peeking at the W3C I see that maybe name is on the way out in favor of id in the future. http://www.w3.org/TR/html4/interact/forms.html#adef-name-FORM
scunliffe
2010-04-27 12:33:37
@David : personnaly, I don't always give id's to my forms elements, but always a name.
Clement Herreman
2010-04-27 12:36:27
In the ancient days when Netscape ruled the land, `name` was used all over the place. Then HTML standardized on using `name` for form **controls** and `id` and `class` for scripting. XHTML 1.0 **removed** the name attribute from forms and XHTML 1.1 removed it from anchors (so you example is invalid if it is supposed to be XHTML (I can't speak for the HTML5 draft without checking, but its a draft anyway)).
David Dorward
2010-04-27 12:44:22
Thanks @David - its an interesting question... XHTML did remove it, but as we now know... XHTML is slowly becoming a dead end in favor of HTML5. In HTML5, the name attribute is still there http://dev.w3.org/html5/spec/Overview.html#the-form-element (and currently does not include any deprecation info or warnings against using it). That all said, since the name attribute isn't actually used in the form submission, an id attribute is likely more useful.
scunliffe
2010-04-27 14:04:23