4
How can I pass the value
from a Javascript variable to a input hidden
?
4
How can I pass the value
from a Javascript variable to a input hidden
?
5
It would be good if you put some code but basically with jquery would be 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>
<input type="hidden" name="campoInvisivel" id="campoInvisivel">
<input type="button" value="Colocar Valor com Jquery" id="botao">
Here the example only with Javascript, remembering that the alert
are only for demonstration, the line on which you pass the value to the input is that 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();">
2
With javascript just assign the value to the attribute value
:
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>
How can I pass an array?
You can use the function join()
that joins the values of the array. I edited the answer @Gonçalo
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" />
Thus the input
will receive as value a JSON that can easily be converted into array on the server or when reading its value.
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
There is no simpler way with javascript?
– Gonçalo
You want only with js, without jquery?
– LocalHost
what you didn’t find simple?
– LocalHost
Exactly, I want it with javascript only.
– Gonçalo
Ready, I edited and left both ways to serve other people later...
– LocalHost