Reputation: 65
function GetWidth(){
var TBL_width = document.getElementById('wrap_tbl').offsetWidth;
return TBL_width;
}
var w = GetWidth();
<input type="hidden" id="tbl" value= w />
Is this possible?
I want to store a JavaScript variable in value attribute of a hidden input element. Please guide me how to do this
Upvotes: 2
Views: 9295
Reputation: 150253
Jquery
version:
$("#tbl").val(w);
Pure JavaScript
version:
document.getElementById("tbl").value = w;
There is no difference between hidden and "unhidden" inputs in this case.
Advice: If your's GetWidth
function has only one line, and the line isn't too much sophisticated, you can extract it from the method.
function setWidth(){
var TBL_width = document.getElementById('wrap_tbl').offsetWidth;
document.getElementById("tbl").value = TBL_width;
}
Upvotes: 8
Reputation: 20163
As the value asignament to the input has already answered, one question,
Do you need it as a param to be sent on submit?
if not, one suggestion: you can allways use the jquery data method
$('body').data('myDesiredName','myDesiredValue');
and to retrieve it
alert($('body').data('myDeesiredName')); //will alert 'myDesiredValue'
this way you can allways store multiple values and variables without the need of hidden elements,
happy coding ;)
Upvotes: 0
Reputation: 160833
You could set the value use javascript.
document.getElementById('tbl').value=w;
If you use jQuery, just $('#tbl').val(w);
Upvotes: 1
Reputation: 16544
This will definitely not work ... and you already realized that :-)
Look what you did with the element "wrap_tbl" ... you accessed it by using document.getElementById(). You can do the exact same thing to access hidden elements
document.getElementById('tbl').value = w;
Upvotes: 2
Reputation: 30666
Use javascript to set the value
property of your hidden element:
var w=GetWidth();
document.getElementById('tbl').value = w;
or jQuery-style:
var w=GetWidth();
$('#tbl').val(w);
Upvotes: 4