How to create a checklist

How to create checkbox list and get selected checkbox value in javascript

+3
source share
2 answers

Assuming 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 get 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(', '));
+6
source

To create an element in the DOM, use document.createElement. To get the selected checkbox value, use element.checkedand / or element.value. To learn more about the HTML DOM, start here .

You might want to use jQuery to make it easier to work with the DOM and move around.

+1
source

Source: https://habr.com/ru/post/1742977/


All Articles