Your issue is because you're providing the string value of the checkbox to slice()
. Instead you need to provide the numerical index of the item to remove in the array. You can use indexOf()
to retrieve that:
var uLIndex = [];
function doSomething(cb) {
if ($(cb).is(":checked")) {
uLIndex.push(cb.value);
console.log(uLIndex);
} else {
uLIndex.splice(uLIndex.indexOf(cb.value), 1); // note the change here
console.log(uLIndex);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="updateListings[]" value="1" onclick="doSomething(this)">
<input type="checkbox" name="updateListings[]" value="2" onclick="doSomething(this)">
<input type="checkbox" name="updateListings[]" value="3" onclick="doSomething(this)">
<input type="checkbox" name="updateListings[]" value="4" onclick="doSomething(this)">
Also note that it's considered better practice to use unobtrusive event handlers over the now outdated on*
event attributes. You can also simplify the code to build the array on each click using jQuery's map()
method, instead of having to track additions/removals manually. Try this:
$('input:checkbox').change(function() {
var uLIndex = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
console.log(uLIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="updateListings[]" value="1">
<input type="checkbox" name="updateListings[]" value="2">
<input type="checkbox" name="updateListings[]" value="3">
<input type="checkbox" name="updateListings[]" value="4">
As with most things that involve jQuery, this version has the advantage of using much simpler logic but being slightly slower (although we're talking milliseconds only). If you need a higher level of performance I'd argue that you probably shouldn't use jQuery at all.