如何将 JS 变量添加到隐藏的表单值中

How to add a JS variable into a hidden form value

我在尝试将 JS 变量放入隐藏字段时遇到问题。

我目前正在这样获取我需要的值:

HTML Snippet
<p class="total-box"><span></span></p>

JS Snippet
var totalDonation = $('.total-box > span');

这给了我需要在页面上显示的内容,但我需要将该值传递到隐藏的表单值中。

我尝试了 SO 和 Google 中的许多方法。像这样:

HTML Snippet
<input type="hidden" name="xyz" id="xyz" value="">

JS Snippet:
document.getElementById('xyz').value = totalDonation;

运气不好。

还考虑过使用 JS 添加隐藏字段,因为它也可以像这样工作:

var input = document.createElement("input");

input.setAttribute("type", "hidden");
input.setAttribute("name", "xyz");
input.setAttribute("value", ('value', document.querySelector('.total-box > span').innerText);

//append to form element that you want .
document.getElementById("xyz").appendChild(input);

我整天都在做这个,看不出哪里错了。如有任何帮助或建议,我们将不胜感激。

这是我正在使用的代码的 CodePen

您正在尝试将输入值设置为 jQuery 对象,该对象是跨度元素。您需要先使用 .text() 来获取跨度的值。在这一行中:

var totalDonation = $('.total-box > span');

只需像这样添加 .text():

var totalDonation = $('.total-box > span').text();

现在应该可以了。

试试这个;代码片段中提到了描述;基本上 获取 span 标签的内部文本并将其分配给隐藏输入。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <p class="total-box"><span>This is the text</span></p>
    <input type="hidden" id="xyz" /> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>

       var totalDonation = $(".total-box>span").text();

       $("#xyz").val(totalDonation); // Sets the text from total donation to your hidden input

       var hiddeninput = $("#xyz").val();

       console.log(hiddeninput); // displays hidden input data


    </script>

</body>
</html>