I am doing an insert and remove value in array. If a value is NOT EXISTED then insert if EXISTED remove it. But I have a simple condition to check whether the selected values are greater than 3. If greater than 3 dont add in the array and make a simple notification.
My problem is I can't remove the value if it is already existed. Here's my simple code:
var limit = 3;
var findValue;
var ids = [];
function findIfExist(selected) {
var findValue = jQuery.inArray(selected, ids);
console.log(findValue);
if(findValue >= 0) {
ids.splice(selected, 1);
} else {
ids.push(selected);
}
}
$('input[name="services[]"]').on('change', function(evt) {
var count = $('input[name="services[]"]:checked').length;
var selected = $(this).val();
if(count > 3) {
bootbox.alert({
title: 'Oops',
message: 'Only 3 services are allowed from the registration',
size: 'small'
});
$(this).prop('checked', false);
findIfExist(selected);
} else {
findIfExist(selected);
}
console.log(ids);
});
Sample output is a simple array with IDs
Can you spot where did I go wrong?