메인>>유머

javascript 선택 체크 올체크

2022-01-25 16:55:00 6011

 
<html>
<head>
    <script>
        function BatchAddToBasket() {
            var questionNums = '';
            var checkboxs = document.getElementsByName('question');
            for (var i = 0; i < checkboxs.length; i++) {
                var isChecked = false;
                if (checkboxs[i].checked) {
                    isChecked = true;
                    break;
                }
            }
            if (!isChecked) {
                alert('请至少选择一个选项');
                return;
            }

            for (var i = 0; i < checkboxs.length; i++) {
                if (checkboxs[i].checked) {
                    questionNums += checkboxs[i].id;
                    if (i < checkboxs.length - 1)
                    questionNums += ',';
                }
            }
            alert('选项id:' + questionNums);
        }

        function SelectAll(obj) {
            if (obj.checked) {
                var checkboxs = document.getElementsByName('question');
                for (var i = 0; i < checkboxs.length; i++) {
                    checkboxs[i].checked = true;
                }
            } else {
                var checkboxs = document.getElementsByName('question');
                for (var i = 0; i < checkboxs.length; i++) {
                    checkboxs[i].checked = false;
                }
            }
        }
    </script>
</head>
<body>
    <div>
        <input type="checkbox" name="checkboxAll" onclick="SelectAll(this)">
        <button onclick="BatchAddToBasket()">加入试题篮</button>
    </div>
    <div>
        <input type="checkbox" name="question" id=0>
        <input type="checkbox" name="question" id=1>
        <input type="checkbox" name="question" id=2>
    </div>
</body>
</html>