开发者

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

$(".s开发者_运维技巧ort").change(function(){

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

    });


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


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.


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

Live Demo


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


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. 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜