简体   繁体   中英

Remove dynamically added variables from Javascript array

I'm working on a project where I generate some checkboxes, with the value based on PHP variables, like this:

<input type="checkbox" value="<?php echo $example; ?>">

I then want to be able to grab the value of a clicked input and add it to a JS array, so that I can post all of the values from any checked checkboxes.

The values are adding to my JS array no problem, but when I try to remove them from the array I'm running into difficulties. If there is an individual element in the array then it will be removed fine, if there are more than that then my code only seems to remove the most recently added.

I think the problem is from the value_array.splice(index, 1); line.

$(document).on('click', '.example-input', function() {

    input = $(this).find('input');

    if(example_condition == true) {
        $(input).prop( 'checked', true );
        value = $(input).val();
        value_array.push(value);
        index = value_array.indexOf(value);
        is_checked = true;
    } else {
        $(input).prop('checked', false);
        is_checked = false;
    }

    if(is_checked == false) {
        if(index !== -1) {
            value_array.splice(index, 1);
        }
    }

    // Post JS array
});

Hopefully, someone can point me in the right direction here.

I've also tried implementing the answer that was given here: How do I remove a particular element from an array in JavaScript? , but it does not seem to work when there are multiple elements in the array.

Thanks.

Here's how I would tackle this: create a function that iterates over the checked boxes and adds to the array, call it when the page loads and when anything changes

 var value_array; $(document).ready(function() { updateValueArray(); $(document).on('change', '.myCheck', function() { updateValueArray(); console.log(value_array); }); }); function updateValueArray() { value_array = []; $('.myCheck:checked').each(function() { value_array.push($(this).attr("value")); }); } 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> </head> <body> <input class="myCheck" type="checkbox" value="1"> <input class="myCheck" type="checkbox" value="2"> <input class="myCheck" type="checkbox" value="3"> <input class="myCheck" type="checkbox" value="4"> <input class="myCheck" type="checkbox" value="5"> <input class="myCheck" type="checkbox" value="6"> <input class="myCheck" type="checkbox" value="7"> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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