How to pass the value of a variable to an input hidden?

4

How can I pass value of a Javascript variable to a input hidden ?

    
asked by anonymous 19.12.2016 / 23:27

3 answers

3

It would be nice if you put some code but basically with jquery it would look like this:

$("#botao").click(function(){
var minhaVariavel="valor";
  alert("Antes de atribuir o valor:"+$("input[name='campoInvisivel']").val());
$("input[name='campoInvisivel']").val(minhaVariavel);
alert("Depois de atribuir o valor:"+$("#campoInvisivel").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="hidden" name="campoInvisivel" id="campoInvisivel">
<input type="button" value="Colocar Valor com Jquery" id="botao">

Here's the only example with JavaScript, remembering that alert is for demonstration only, the line on which you pass the value to the input is this document.getElementById("campoInvisiveljs").value=minhaVariavel; . Below is the complete code

// Aqui é só com js
function passarValor(){
var minhaVariavel="valor";
alert("Antes de passar o valor:"+ document.getElementById("campoInvisiveljs").value);
document.getElementById("campoInvisiveljs").value=minhaVariavel;
alert("Depois de passar o valor:"+document.getElementById("campoInvisiveljs").value);
}
   <input type="hidden" name="campoInvisiveljs" id="campoInvisiveljs">
   <input type="button" value="Colocar Valor com Java Script" id="botao" onClick="passarValor();">
    
19.12.2016 / 23:34
2

With javascript, just assign the value to the value attribute:

var variavel = ["a", "b", "c"];
document.getElementById("input_hidden_id").value = variavel.join("");

Example:

    var variavel = ["a", "b", "c"];
    document.getElementById("input_hidden_id").value = variavel.join("");

    function verValor() {
      document.write(document.getElementById("input_hidden_id").value);
    }
<input id="input_hidden_id" type="hidden" value="123" />
<button onclick="verValor()">Ver Valor</button>
    
19.12.2016 / 23:48
2

You can do it like this:

var dados = ['eu', 'tu', 'ele'];
var input = document.getElementById('escondido');
input.value = JSON.stringify(dados);
<input type="hidden" id="escondido" />

In this way, input will receive as value a JSON that can easily be redirected to the server or when reading the value of it.

    
20.12.2016 / 08:37