0

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?

1 Answer 1

3

Array#splice uses the index of the element to remove, not the element itself.

ids.splice(selected, 1);

Here, you're passing the element to the splice(). Use the index findValue.

ids.splice(findValue, 1);
Sign up to request clarification or add additional context in comments.

1 Comment

@Jerielle Welcome :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.