As per multiple elementByID within a single variable?

1

I wanted to know if I have how and how I can put multiple elementDocumentID inside a single variable.

Example:

The code is to do validation, the code looks 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;'
    
asked by anonymous 10.07.2017 / 18:47

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

    
10.07.2017 / 19:10
0

You can get all inputs using document.querySelectorAll , then the array of inputs can use the reduce function of the array to transform the inputs into a obj.name => value object, this works generically for how many inputs you have < p>

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"/>
    
10.07.2017 / 19:50