【问题标题】:How to keep a stored array of input checkbox value?如何保留输入复选框值的存储数组?
【发布时间】:2016-03-14 19:41:01
【问题描述】:

我有一个作为类别过滤器的输入复选框。我只想将输入复选框的值存储在一个数组中,这些值在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>

jQuery:

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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    }
});

【问题讨论】:

    标签: javascript jquery arrays checkbox each


    【解决方案1】:

    检查它,兄弟,它的工作方式如你所愿

    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/

    【讨论】:

    • 完美运行!谢谢!
    • 每次复选框更改时循环冗余。刚开始做一个,然后继续验证
    【解决方案2】:

    您可以通过mapcall 轻松完成

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

    (Updated jFiddle)

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

    【讨论】:

    • 其实不要使用条件返回,你应该总是返回一个值,true或者false
    • @Mottie 通过返回false 不会false 值最终出现在结果数组中吗?
    • 是的,但是如果您无法分辨第二个 true 的含义,那么生成的数组有什么用?
    • @Mottie 第二个true?我用我理解的是 OP 的预期功能做了一个 jFiddle。
    • @TheAmazingKnight 当然。首先,map 不是 jQuery 的东西,它通常在大多数语言中实现,并且在函数式编程范式中很典型。在其典型形式中,它接受一个数组(或一些可迭代的)和一个函数作为参数。然后,它将函数应用于数组的每个元素,生成一个新数组,其中包含对每个元素的操作结果。这里的操作只是提取val(),而我们操作的集合就是选中的checkbox的选择。
    【解决方案3】:

    编辑

    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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    }
    });
    

    【讨论】:

    • 这可行,但在初始加载时,checkedAttr 为空,然后在检查完所有值后存储值。
    • @TheAmazingKnight 已编辑,开头只有一个额外的循环
    【解决方案4】:

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

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

    【讨论】:

    • 当问题没有用下划线标记时,为什么要给出使用下划线的答案?
    • 我的错。无论如何,它与 jQuery 非常相似。更新了我的答案
    【解决方案5】:

    使用$.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/

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 2017-03-17
      • 2016-03-22
      • 1970-01-01
      • 2017-02-16
      • 2014-07-06
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      相关资源
      最近更新 更多