开发者

How to create list of checkboxes

How to create a list of checkbox and retri开发者_运维技巧eve 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.


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜