Convert Nodelist to String(?) / Capturing Checkbox values (javascript)

Asked

Viewed 25 times

0

I am creating a form and would like to capture values from it, and while submitting I review it on the screen.

However one of the fields is checkbox and the user can choose more than one option, as I used Document.queryselectorAlll it returns me a nodeList. And (as a beginner) I’m not able to convert these values into string or capture these values.

How can I do it? I need to capture this value (or values) of this nodeList. I am trying from the code below:


document.querySelector('.formcadastro').addEventListener('submit', function(event){

    event.preventDefault();

    var campos = [
        document.querySelector('#nome-completo'),
        document.querySelector('input[name="generos"]:checked'),
        document.querySelector('#nascimento'),
        document.querySelector('#cpf'),
        document.querySelector('#rg'),
        document.querySelector('#carga'),
        document.querySelector('#salario'),
        document.querySelector('#predio'),
        document.querySelectorAll('input[name="transporte"]:checked')
    
    ]

    var tr = document.createElement('tr');

    campos.forEach(function(campo){

        var td = document.createElement('td');

        td.textContent = campo.value;
        tr.appendChild(td);
        
    });

    tbody.appendChild(tr);
    console.log(campos);
    
});

returning:

(9) [input#nome-completo.form-control, input#feminino.form-check-input, input#nascimento.form-control, input#cpf.form-control, input#rg.form-control, input#carga.form-control, input#salario.form-control, input#predio.form-control, NodeList(1)]

0: input#nome-completo.form-control
1: input#feminino.form-check-input
2: input#nascimento.form-control
3: input#cpf.form-control
4: input#rg.form-control
5: input#carga.form-control
6: input#salario.form-control
7: input#predio.form-control
8: NodeList(1)
0: input#bhbus.form-check-input
length: 1
__proto__: NodeList
length: 9
__proto__: Array(0)
  • 1

    and how do you expect the data? a list for example "1, 3, 4"? or array [1, 3, 4]?

  • That, as a list.

1 answer

-1

You can "spread" (spread) eternal objects like Arrays and Nodelists with the operator ....

When you use this operator, each item of the iterable object is passed as a different variable to a function, or to an array initialization, as is your case.

I believe that what you want to do can be obtained this way:

var campos = [
    document.querySelector('#nome-completo'),
    document.querySelector('input[name="generos"]:checked'),
    document.querySelector('#nascimento'),
    document.querySelector('#cpf'),
    document.querySelector('#rg'),
    document.querySelector('#carga'),
    document.querySelector('#salario'),
    document.querySelector('#predio'),
    ...document.querySelectorAll('input[name="transporte"]:checked')
]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.