Why does JSON.stringify () return an empty array?

3
/* Validar checkboxes clickeados */
var checkboxes = document.querySelectorAll('.single-checkbox');
var clickeados = new Array();

checkboxes.forEach(elem => {
    elem.addEventListener('change', (event) => {
        event.stopPropagation();
        if(elem.checked) {
           if(!clickeados.includes(elem)){
                   clickeados.push(elem);
//                   console.log(clickeados);
           }
        }
        else{
            if(clickeados.includes(elem)){
                   clickeados.pop(elem);
//                   console.log(clickeados);
            }
        }
    });
});

/* Validar cuantos gustos fueron seleccionados antes de hacer el submit */
$('#vasitoForm').on('submit', (event) => {
    if(clickeados.length == 0){
        event.preventDefault();
        document.getElementById("errorGustos").innerHTML = "Debe seleccionar por lo menos un gusto";
    }
    else if(clickeados.length > 0 && clickeados.length < 3){
    console.log(clickeados);
        var myArray = JSON.stringify(clickeados);
//        $('#vasitoForm').attr('action', myArray + '/pedido');
        console.log(myArray);
    }
});

The console.log (clicked) prints the input's array perfectly, but when I want to convert it to JSON and reprint it the JSON comes out empty ...

  

Array [input.single-checkbox] home.js: 59: 5

     

[{}] home.js: 62: 9

    
asked by Nacho Zve De La Torre 26.11.2018 в 17:53
source

1 answer

4

When JSON.stringify iterates your array to convert it to string, it finds the input.single-checkbox element that is an HTML node and does not know how to convert it to string, so it remains an empty object.

JSON.stringify([elem])
// "[{}]"

I recommend that you better arm your own object only with the properties that you use from the HTML node and that is what you convert through JSON.stringify

JSON.stringify([{props:1}])
// "[{"props":1}]"
    
answered by 26.11.2018 / 18:13
source