How to put several elementByID within one variable?

Asked

Viewed 138 times

1

I wanted to know if there is a way and how to put several elementDocumentID within a single variable.

Example:

The code is for validation, the code is like this:

var email = document.getElementById("email").value;
var nome=document.getElementById("nome").value;
var senha=document.getElementById("senha").value;
var rep_senha=document.getElementById("rep_senha").value;`
  • 1

    what exactly are you trying to do? Take the data from a <form>?

  • Why exactly?

2 answers

2


Just use a Javascript object

dados = {
    email : document.getElementById("email").value,
    nome : document.getElementById("nome").value,
    senha : document.getElementById("senha").value,
    rep_senha : document.getElementById("rep_senha").value
}

And to access:

dados.email

Or whatever field you need

0

You can pick up all inputs using the document.querySelectorAll, after with the input array you can use the function reduce array to transform inputs into an object obj.name => value, this works generically for how many inputs you have

function data(){
	var form = document.querySelectorAll('input');
	var inputs = Array.from(form);
	return inputs.reduce((valorAnterior, valorAtual, indice, array) => {
		valorAnterior[valorAtual.name] = valorAtual.value;
		return valorAnterior;
	},{});
}

console.log(data());
<input type="text" name="email" value="valueEmail"/>
<input type="text" name="nome" value="valueNome"/>
<input type="password" name="senha" value="valueSenha"/>
<input type="password" name="rep_senha" value="valueSenha"/>

Browser other questions tagged

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