js获取input checkbox的选中值

时间:2021-04-19 19:32:42

 

HTML代码:

<form action="/test/action" method="get">
    <input type="checkbox" name="myname" value="1"/>1
    <input type="checkbox" name="myname" value="2"/>2
    <input type="checkbox" name="myname" value="3"/>3
    <input type="checkbox" name="myname" value="4"/>4
    <input type="checkbox" name="myname" value="5"/>5
    <input type="button" οnclick="formSubmit()" value="提交" />
</form>

js代码:

<script>
    function formSubmit() {
        var obj = document.getElementsByName("myname");
        var check_arr = [];
        for (var i = 0; i < obj.length; i++) {
            if (obj[i].checked)
                check_arr.push(obj[i].value);
        }
        alert(check_arr);
    }
</script>