如何保留输入复选框值的存储数组

How to keep a stored array of input checkbox value?

本文关键字:复选框 存储 数组 输入 何保留 保留      更新时间:2023-09-26

我有一个充当类别过滤器的输入复选框。我只想将输入复选框的值存储在在var checkedAttr中选中的数组中。然后测试任何已经存在的值是否与数组中的任何值匹配,以及是否确实删除了它。我遇到的问题是...单击输入复选框时,它将存储与$each循环或输入复选框一样多的次数,在本例中为(三次)。我还注意到,当取消选中多个,然后重新选中同一个时,它会在$each循环中多次添加值,并且会以某种方式绕过从数组中删除的值。我只想在每次用户检查或取消选中时从数组中添加(选中的值)/删除(未选中的值)。

这是一个jsfiddle。

.HTML:

<div id="category-list">
     <h1>Categories</h1>
     <input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
     <input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
     <input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading
</div>

j查询:

var checkedAttr = []; // array for checked attributes
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function() 
{
    var value = $(this).val();
    if($(this).is(':checked')) // checked
    {
        console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!');
        $('#category-list :checkbox').each(function(i, item){ // loop thru the input checkboxes
            if(!(value === $(item).val())) // check if the current value does NOT match that already stored in array
            {
                checkedAttr.push(value); // add value to array
                console.log("checkedAttr:", checkedAttr);
            }
            else // if it does match...
            {
                checkedAttr.splice(i, 1);// remove it from array  
                console.log("checkedAttr:", checkedAttr);
            }
        });
        // check which attributes are checked and store in 'checkedAttr' array
        //$('input[name=filter]').each(function(i, item){
        //});
    } 
    else // unchecked
    {
        console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    }
});

检查一下兄弟,它随心所欲地工作

var checkedAttr = [];
$('#category-list :checkbox').change(function() 
{
    checkedAttr = [];
    $('#category-list :checkbox').each(function(i, item){
        if($(item).is(':checked'))
        {
            checkedAttr.push($(item).val()); 
        }
    });
   console.log("checkedAttr:", checkedAttr);
});

您也可以在 JSFiddle 中检查它

https://jsfiddle.net/xdrLra77/

您只需map调用即可完成

var checkedAttr = [];
    
$('#category-list :checkbox').change(function() {
    checkedAttr = $('#category-list :checked').map(function(){
        return $(this).val();
    }).get();
    
    console.log(checkedAttr);
});

(更新的 jFiddle)

(编辑:更好的是,将条件放在jQuery选择器中)

已编辑

var checkedAttr = []; // array for checked attributes
//first load, see what is checked
$('#category-list :checkbox').each(function(){
 if($(this).is(':checked')) // checked
 checkedAttr.push($(this).val())
})

// change event listener for whenever one or more of the following     checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function() 
{
var value = $(this).val();
var position = checkedAttr.indexOf($(this).val());
if($(this).is(':checked')) // checked
{
    if(position == -1){ // dnot exist in array, add
        checkedAttr.push($(this).val());
      console.log("checkedAttr:", checkedAttr);
    }else{ // exist in array, do nothing
        //do nothing
   }
   console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
} 
else // unchecked
{
    if(position == -1){ // dont exist in array, do nothing
        //do nothing
    }else{ // exist in array, remove
        checkedAttr.splice(position,1);
        console.log("checkedAttr:", checkedAttr);
    }
    console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});

您可以使用 $('.categories:checked') 获取选中的元素。然后,您可以遍历这些值以获取实际值

var checkedValues= $('.categories:checked');
var valuesArray=[];
$.each(checkedValues, function(checkedValue){
valuesArray.push(checkedValue.value)
}

使用 $.inArray

if (index === -1  && $(this).is(':checked')) {
    checkedAttr.push(value); // add value to array
    console.log("added:", checkedAttr);
 } else if (index !== -1 && ! $(this).is(':checked')) {
    checkedAttr.splice(index, 1);// remove it from array                
    console.log("removed:", checkedAttr);
}

修正小提琴:https://jsfiddle.net/o1rmz1o1/4/