madphp
madphp

Reputation: 1764

checkbox value array add and remove from array

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());
        });

    });

Upvotes: 1

Views: 7888

Answers (5)

Levi Morrison
Levi Morrison

Reputation: 19552

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.

Upvotes: 1

Frenchi In LA
Frenchi In LA

Reputation: 3169

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. 

Upvotes: 0

RET
RET

Reputation: 9188

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() ?

Upvotes: 1

Bassem
Bassem

Reputation: 3175

-- 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/

Upvotes: 2

DJafari
DJafari

Reputation: 13535

$(".sort").change(function()
{
    var arr_sort = new Array();
    $(".sort").each(function()
    {
        if( $(this).is(':checked') )
        {
            arr_sort.push($(this).val());
        }
    });
});

Live Demo

Upvotes: 1

Related Questions