How to create a list of checkbox and retrieve selected checkbox value in javascript
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(', '));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With