How to check multiple checkboxes with JavaScript?

Try this: Fiddle

jQuery:

var selected = [];
$('.data input:checked').each(function() {
    selected.push($(this).val());
});

Javascript:

var checkboxes = document.getElementsByName('employee');
var selected = [];
for (var i=0; i<checkboxes.length; i++) {
    if (checkboxes[i].checked) {
        selected.push(checkboxes[i].value);
    }
}

var elements=document.getElementsByName('employee');

should return you an array of the elements you require

DEMO


In case you just want to use pure/vanilla JS, here is an example:

HTML HEAD

<script type="text/javascript">
function getCheckedCheckboxesFor(checkboxName) {
    var checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'), values = [];
    Array.prototype.forEach.call(checkboxes, function(el) {
        values.push(el.value);
    });
    return values;
}
</script>

HTML BODY

<div class="data">    
    <span>
    <input name="employee" type="checkbox" value="Alex"/>
    <label for="employee">Alex</label>
    </span> 

    <span>
    <input name="employee" type="checkbox" value="Frank"/>
    <label for="employee">Frank</label>
    </span>    

    <span>
    <input name="employee" type="checkbox" value="Mark"/>
    <label for="employee">Mark</label>
    </span>

    <input type="button" onclick="alert(getCheckedCheckboxesFor('employee'));" value="Get Values" />
</div>

JS Fiddle link: http://jsfiddle.net/dY372/


Using querySelectorAll:

var checked = document.querySelectorAll('[name="employee"]:checked');

Support: IE9+.