Pass a javascript variable value into input type hidden value

后端 未结 8 1240
情歌与酒
情歌与酒 2020-11-27 11:38

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 varia

8条回答
  •  孤城傲影
    2020-11-27 11:56

    if you already have that hidden input :

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

    if not, you can create one, add it to the body and then set it's value :

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

    And then you can use(depending on the case) :

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

提交回复
热议问题