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.