2
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

1
  • 2
    I think you would profit from reading some basic information about JavaScript and DOM. Commented Jan 12, 2012 at 10:33

5 Answers 5

8

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

You forgot the #: $("#tbl")
4

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);

Comments

2

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;

Comments

1

You could set the value use javascript.

document.getElementById('tbl').value=w;

If you use jQuery, just $('#tbl').val(w);

Comments

0

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 ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.