简体   繁体   English

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

[英]Removing value from array according to index using splice()

I have 4 checkboxes.我有 4 个复选框。 I add values of them to an array on check.我在检查时将它们的值添加到数组中。 It looks like this.看起来像这样。

Here are the four checkboxes I have.这是我的四个复选框。

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

Once I check all four of them, the array becomes,一旦我检查了所有四个,数组就变成了,

["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 .我使用splice()但它总是删除第一个索引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>

You used the wrong way to find index in your code.您使用错误的方法在代码中查找索引。 If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.如果您使用元素索引,它会避免在数组中使用真正的索引并给出错误的 output。检查下面的代码,它可能适合您的要求。

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

    <script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<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 = selectedValues.indexOf(this.value);

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

                        }
                    }
                }
            }


        }

        getLevels();

    </script>

Add change handler to the inputs and use jQuery map to get the values of the checked inputs.将更改处理程序添加到输入并使用 jQuery map 获取已检查输入的值。

 var levels $('#checkArray input').on('change', function () { levels = $('#checkArray input:checked').map(function () { return this.value }).get() console.log(levels) }).eq(0).change()
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <fieldset id="checkArray"> <input type="checkbox" value="degree" checked> <input type="checkbox" value="pgd"> <input type="checkbox" value="hnd"> <input type="checkbox" value="advdip"> </fieldset>

my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response.我的方法是添加一个事件处理程序,该事件处理程序在单击任何这些输入时读取所有选中的值,并在记录响应之前清空数组。 no need to add any dependencies with this one无需为此添加任何依赖项

Hope this is what you are looking for希望这就是您要找的

 function getLevels() { let checkboxContainer = document.getElementById("checkboxContainer"); let inputs = checkboxContainer.querySelectorAll("input"); let checked = []; inputs.forEach( (input) => { checked = []; input.addEventListener( 'click', () => { checked = []; inputs.forEach( (e) => { e.checked? checked.push(e.value): null; }) console.log(checked); }); }); } getLevels();
 <div id="checkboxContainer"> <input type="checkbox" value="degree" > <input type="checkbox" value="pgd"> <input type="checkbox" value="hnd"> <input type="checkbox" value="advdip"> </div>

I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.我不知道这是否是您需要的,以显示所选值的数组,如果您愿意,可以调用在支票上计算的 function。

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <fieldset id="checkArray"> <input type="checkbox" value="degree" checked> <input type="checkbox" value="pgd"> <input type="checkbox" value="hnd"> <input type="checkbox" value="advdip"> </fieldset> <button onclick="getLevels()">getLevels</button> <script> function getLevels() { var levels = []; $.each($("input:checked"), function() { levels.push(($(this).val())); }); console.log(levels); } getLevels(); </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM