0

I have this code to put it in array when user checks the check box.. but when user unchecks the check box how do I need to remove from the Array?

 $(function () {
   var listval = [];
        $('input[name="checkedRecords"]').bind('click', function () {
            if ($(this).is(':checked')) {
                listval.push($(this).val());
            }
            else {
                //How to remove the Unchecked item from array..
            }
        });
    });

Thanks in advance.

2

1 Answer 1

7

If you have an array

var mylist = ['a','b','c','d'];

To remove the value 'b':

if ((index = mylist.indexOf('b')) !== -1)
    mylist.splice(index, 1);

Results in:

mylist == ['a','c','d'];

For your application:

 $(function () {
   var listval = [];
        $('input[name="checkedRecords"]').bind('click', function () {
            if ($(this).is(':checked')) {
                listval.push($(this).val());
            }
            else {
                if ((index = listval.indexOf($(this).val())) !== -1) {
                    listval.splice(index, 1);
                }
            }
        });
    });
Sign up to request clarification or add additional context in comments.

5 Comments

I updated the answer to spoon-feed you the answer so you don't have to put an iota of thought into it.
I am getting a page error saying Object does not support this property or method.
Are you sure that error is coming from this code? Do a console.log($(this)) at the top of the function and see what is triggering the click
I am sure error is coming from this line of code if ((index = listval.indexOf($(this).val())) !== -1)
You could use $.inArray instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.