使用splice()根据索引从数组中删除值

我有4个复选框。我将它们的值添加到检查的数组中。看起来像这样。

这是我拥有的四个复选框。

<input type="checkbox" value="degree">
<input type="checkbox" value="pgd"> 
<input type="checkbox" value="hnd"> 
<input type="checkbox" value="advdip">

一旦我检查了所有四个,数组就变成了

["degree", "pgd", "hnd", "advdip"]

When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!

<input type="checkbox" value="degree">
    <input type="checkbox" value="pgd"> 
    <input type="checkbox" value="hnd"> 
    <input type="checkbox" value="advdip">

<script>

        function getLevels() {
             // get reference to container div of checkboxes
            var con = document.getElementById('course-levels');
            // get reference to input elements in course-levels container
            var inp = document.getElementsByTagName('input');

            // create array to hold checkbox values
            var selectedValues = [];

            // collect each input value on click
            for (var i = 0; i < inp.length; i++) {
                // if input is checkbox
                if (inp[i].type === 'checkbox') {
                    // on each checkbox click
                    inp[i].onclick = function() {
                        if ($(this).prop("checked") == true) {

                            selectedValues.push(this.value);
                            console.log(selectedValues);
                        }
                        else if ($(this).prop("checked") == false) {
                            // get index number
                            var index = $(this).index();

                            selectedValues.splice(index, 1);
                            console.log(selectedValues);

                        }
                    }
                }
            }


        }

        getLevels();

    </script>
评论