简体   繁体   English

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

[英]How to add a JS variable into a hidden form value

I'm having a problem trying to get a JS variable into a hidden field. 我在尝试将JS变量放入隐藏字段时遇到问题。

I'm currently getting the value I need like this: 我目前正在获得所需的价值,例如:

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

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

This gives me what I need to display on the page, but I need to pass that value into a hidden form value. 这给了我我需要在页面上显示的内容,但是我需要将该值传递给隐藏的表单值。

I tried many approaches from SO and Google. 我尝试了SO和Google的许多方法。 Like this: 像这样:

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

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

No Luck. 没运气。

Also thought about adding the hidden field using JS as that would work too like this: 还考虑过使用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);

I've been at this all day and can't see where I'm going wrong. 我整天都在这里,看不到我要去哪里错了。 Any help or suggestions would be appreciated. 任何帮助或建议,将不胜感激。

Here is a CodePen of my code I'm working with. 这是我正在使用的代码的CodePen

You're trying to set an input value to a jQuery object which is a span element. 您正在尝试将输入值设置为span元素的jQuery对象。 You need to use .text() to get the value of the span first. 您需要使用.text()首先获取跨度的值。 In this line: 在这一行:

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

Just add .text() like so: 只需添加.text()就像这样:

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

And now it should work. 现在应该可以了。

Try this; 尝试这个; the description is mentioned in the code snipp ; 代码片段中提到了该描述; basically get the inner text of the span tag and assign it to the hidden input. 基本上获取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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM