1

I have the following code that pushes check-box values to an array. I want to be able to remove the values from array if check-boxes are unchecked. Can anyone tell me how to do this.

var arr_sort = new Array();

$(".sort").change(function(){

        $.each($("input[name='sort']:checked"), function() {
           arr_sort.push($(this).val());
        });

    });

5 Answers 5

2

-- Disregard the answer if the triggering event isn't the checkbox's click event.

You should create a small function that will remove the value from the array upon the checkbox's click event trigger.

function removeVal(arr, val)
{
    for(var i = 0; i < arr.length; i++)
    {
        if (arr[i] == val)
            arr.splice(i, 1);
    }
}

Find the working example below:

http://jsfiddle.net/7NcuD/

Sign up to request clarification or add additional context in comments.

Comments

1

Answer: http://jsfiddle.net/morrison/S3e2f/

Notes:

  • Use a key/value system. This way you can know which array item to set or unset. This probably means giving your checkboxes names.
  • Don't loop over the array each time every time something changes. That's bad design and could lead to bad performance. I restructured the HTML.

2 Comments

I see what you mean now. I have used your solution now, maybe you can answer this question. stackoverflow.com/questions/7314060/… Is it bad form to change answers?
No. Changing answers is just fine.
1
$(".sort").change(function()
{
    var arr_sort = new Array();
    $(".sort").each(function()
    {
        if( $(this).is(':checked') )
        {
            arr_sort.push($(this).val());
        }
    });
});

Live Demo

8 Comments

ok, i see the solution in your answer, i need to recreate the array inside the .change(). Your solution works too. Thanks!
Won't this limit the scope of the arr_sort variable to the change() function? I don't think that's what you want.
@RET : Becuase array values is dupplicated, but if be this, array is empty before fill
This is BAD programming design. You don't need to recreate the array each time. That's much heavier than simply modifying one value.
@madphp See stackoverflow.com/questions/7313695/… for a proper answer.
|
1

Since you're looping through the sort checkboxes on any change, surely the simplest fix is to empty out the arr_sort array just before the $.each() ?

Comments

0

you can use map or grep to remove element in the array that don't satisfy your criteria. something like :

var arr_check = $.grep(arr_sort,function(value){return value == ?? ;}); // since you're saving $(this).val() your array has checkbox value, so you have to filter with those values. 

Comments

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.