Mohit Jain
Mohit Jain

Reputation: 43929

How to create list of checkboxes

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

Upvotes: 4

Views: 20051

Answers (3)

scunliffe
scunliffe

Reputation: 63580

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(', '));

Upvotes: 7

mplungjan
mplungjan

Reputation: 177691

More modern answer

document.querySelector("[name=test]").addEventListener("click", 
  e => {
    let tgt = e.target;
    if (tgt.name==="colors") {
      let checked = [...e.currentTarget.querySelectorAll(`[name=${tgt.name}]:checked`)];
      document.getElementById("res").innerHTML = checked.map(inp => inp.value).join(", ")
    }   
})
<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>
<span id="res"></span>

Upvotes: 1

BalusC
BalusC

Reputation: 1108642

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.

Upvotes: 1

Related Questions