mardi 17 décembre 2019

How to get values in an object array from nested checkboxes?

In my website i have a dynamically generated checkbox tree from a JSON now i need to get checked values in the following object that will become an array of objects like this:

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

negozio is the top parent checkbox cassa is the first child checkbox that could contain another checkbox level called operatore, actually i was trying to do something like this inside 'on.change' method on checkbox input

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

The issue is that with the following method operatore and CS are in separated levels so the object looks like the following: [{ cassa: [{ CS: 1 }, { operatore: [] }], negozio: "0" }] when it should be [{ cassa: [{ CS: 1, operatore: [] }], negozio: "0" }]

Here is a JSFiddle with live example with HTML and JS code




Aucun commentaire:

Enregistrer un commentaire