最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Set hidden input value with javascript - Stack Overflow

programmeradmin5浏览0评论
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

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

Share Improve this question edited Nov 26, 2018 at 18:45 Brock Adams 93.5k23 gold badges240 silver badges304 bronze badges asked Jan 12, 2012 at 10:27 sandipsandip 653 silver badges6 bronze badges 1
  • 2 I think you would profit from reading some basic information about JavaScript and DOM. – Felix Kling Commented Jan 12, 2012 at 10:33
Add a ment  | 

5 Answers 5

Reset to default 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;
}

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

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;

You could set the value use javascript.

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

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

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

发布评论

评论列表(0)

  1. 暂无评论