Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create list of checkboxes

How to create a list of checkbox and retrieve selected checkbox value in javascript

like image 403
Mohit Jain Avatar asked Feb 27 '23 03:02

Mohit Jain


2 Answers

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(', '));
like image 79
scunliffe Avatar answered Mar 07 '23 18:03

scunliffe


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.

like image 24
BalusC Avatar answered Mar 07 '23 19:03

BalusC