在jQuery中,复选框在空数组中推入它们的值,但在未选中时弹出或移动值

Checkboxes that push their value in an empty array but pop or shift the value when unchecked in jQuery

本文关键字:移动 复选框 jQuery 数组      更新时间:2023-09-26

所以我有一个复选框列表,我把它们的值推到一个仅限于3个选择的数组中。这些选择以div的形式显示在页面上。推动部分工作得很好…我遇到的问题是,当我取消选择或取消复选框时,我希望值从数组中弹出或删除,这反过来又从视图中删除或分离它们。

/* checkboxes */
    selections = new Array();   
    $("input[type='checkbox']").change(function () {
        var maxAllowed = 3;
        var cnt = $("input[type='checkbox']:checked").length;  
        var checkIt = $("input[type='checkbox']");
        var chkboxVal = $(this).val();
        //reset selections counter
        if (cnt <= maxAllowed) {
          $('.selCount .counter').html(selReset-cnt);
          selections.push(chkboxVal);
        } else if (cnt > maxAllowed) {
          $(this).prop("checked", "");
          $(this).unbind("click");
          $(this).css("cursor","default");
        }
        var Item1 = selections[0];
        var Item2 = selections[1];
        var Item3 = selections[2];
        var bindedChoice1 = $('<div class="sel1">'+Item1+'</div>');
        var bindedChoice2 = $('<div class="sel2">'+Item2+'</div>');
        var bindedChoice3 = $('<div class="sel3">'+Item3+'</div>');
        //Index of check
        if (cnt == 1) {
           $(".catSelBar").append(bindedChoice1);
           console.log(selections);
        }
        if (cnt == 2) {
           $(".catSelBar").append(bindedChoice2);
           console.log(selections);
        }
        if (cnt == 3) {
           $(".catSelBar").append(bindedChoice3);
           console.log(selections);
        } 

    if(!$(this).prop("checked") && cnt == 1 && $('.catSelBar div').hasClass("sel1")) {
            $(".sel1").detach();
            selections.pop();
           console.log(selections);
        }
        if(!$(this).prop("checked") && cnt == 1 && $('.catSelBar div').hasClass("sel2")){
            $(".sel2").detach();
           selections.pop();
           console.log(selections);
        }
        if(!$(this).prop("checked") && cnt == 2 && $('.catSelBar div').hasClass("sel3")) {
            $(".sel3").detach();
           selections.pop();
           console.log(selections);
        }

    }); //checkbox change function

当我过去做这样的事情时,有时我会重新构建选择数组。

下面是一些示例代码:
$(function() {
    var selections = [],
        render_selections = function() {
            $('#selections').html(selections.join(', '));
        };
    $('input[type="checkbox"]').change(function() {
        selections = $.map($('input[type="checkbox"]:checked'), function(a) { return a.value; })
        render_selections();
    });
});

,这里是一个示例小提琴:http://jsfiddle.net/v4w25pe5/