如何使用JavaScript检查多个复选框?

时间:2014-04-19 20:16:00

标签: javascript arrays checkbox

我有多个复选框

<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>
</div>

如何查找所有选中的复选框并创建带有检查结果的json或数组?

5 个答案:

答案 0 :(得分:9)

如果你只想使用pure / vanilla JS,这里有一个例子:

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小提琴链接:http://jsfiddle.net/dY372/

答案 1 :(得分:6)

试试这个: 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);
    }
}

答案 2 :(得分:2)

使用querySelectorAll

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

支持:IE9 +。

答案 3 :(得分:1)

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

应该返回一个你需要的元素数组

DEMO

答案 4 :(得分:0)

function checked(){

    var items=getElementsByname('checkbox');

    var selectedlist=[];

    for(var i=0; i<items.length; i++)       
    {
        if(items[i].type=='checkbox' && items[i].checked==true)                 
            selectedlist+=items[i].value+"\n";
    }

    alert(selectedlist);
}