【问题标题】:How to get values in an object array from nested checkboxes?如何从嵌套复选框中获取对象数组中的值?
【发布时间】:2020-04-09 17:24:36
【问题描述】:

在我的网站中,我有一个从 JSON 动态生成的复选框树,现在我需要在以下对象中获取选中的值,该对象将成为这样的对象数组:

var config = {
    negozio: 1,
    cassa: [{
        CS: 1,
        operatore: []
    }]    
};

negozio 是顶级父复选框 cassa 是第一个子复选框,它可以包含另一个称为operatore 的复选框级别,实际上我试图在复选框输入的'on.change' 方法中执行类似的操作

var config = [];
$(".nav").on("change", "input[type='checkbox']", function () {


    var selezione = {
        cassa: [{
            operatore: []
        }]
    };

    $(".check-negozio").each(function () {
        if (this.checked || this.indeterminate) {
            const npv = $(this).attr('data-npv');
            if (npv != null)
                selezione.negozio = npv;
            $(".check-cassa").each(function () {
                if (this.checked || this.indeterminate) {
                    const cs = $(this).attr('data-cs');
                    if (cs != null)
                        selezione.cassa.push({ CS: cs });
                    $(".check-operatore").each(function () {
                        if (this.chedked) {
                            const op = $(this).attr('data-op');
                            if (op != null)
                                selezione.cassa.operatore.push({ OP: op });
                        }
                    })
                }
            })
        }
    })

    config.push(selezione);
    console.log(config)
    //$.post("api/prodotti/post/", config);
});

问题在于,使用以下方法,operatore 和 CS 处于分离的级别,因此对象如下所示:[{ cassa: [{ CS: 1 }, { operatore: [] }], negozio: "0" }] 何时应该是 [{ cassa: [{ CS: 1, operatore: [] }], negozio: "0" }]

这是一个JSFiddle 带有 HTML 和 JS 代码的实时示例

【问题讨论】:

    标签: javascript jquery multidimensional-array checkbox


    【解决方案1】:

    根据上面的代码,您首先将 CS 对象推送到 operatore 对象到 cassa 数组中。相反,您可以尝试准备好 CSoperatore 值,然后将它们绑定到一个对象中并推入 cassa 。像这样:

    selezione.cassa.push({ CS: cs , operatore: op });
    

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2021-09-21
      • 2013-10-11
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 2016-01-01
      • 1970-01-01
      相关资源
      最近更新 更多