Pass a javascript variable value into input type hidden value

KaH*_*HeL 62 html javascript

I would like to assign value of product of two integer numbers into a hidden field already in the html document. I was thinking about getting the value of a javascript variable and then passing it on a input type hidden. I'm having a hard time to explain but this is how it should work:

Script Example

 <script type="text/javascript">
 function product(a,b){
      return a*b;
 }
 </script>
Run Code Online (Sandbox Code Playgroud)

above computes the product and i want the product to be in hidden field.

<input type="hidden" value="[return value from product function]">
Run Code Online (Sandbox Code Playgroud)

How is this possible?

Dar*_*rov 120

You could give your hidden field an id:

<input type="hidden" id="myField" value="" />
Run Code Online (Sandbox Code Playgroud)

and then when you want to assign its value:

document.getElementById('myField').value = product(2, 3);
Run Code Online (Sandbox Code Playgroud)

Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load event.

  • 最好的答案是最简单的答案. (3认同)

gio*_*_13 9

如果您已经有隐藏的输入:

function product(a, b) {
   return a * b;
}
function setInputValue(input_id, val) {
    document.getElementById(input_id).setAttribute('value', val);
}
Run Code Online (Sandbox Code Playgroud)

如果没有,你可以创建一个,将其添加到正文然后设置它的值:

function addInput(val) {
    var input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('value', val);
    document.body.appendChild(input);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用(取决于具体情况):

addInput(product(2, 3)); // if you want to create the input
// or
setInputValue('input_id', product(2, 3)); 
Run Code Online (Sandbox Code Playgroud)