[英]Can't Pass Cookie into Hidden Form Field with Javascript or jQuery
I have some Javascript or jQuery that I am using to pass information stored in a cookie into a hidden form field on my website.我有一些 Javascript 或 jQuery 用于将存储在 cookie 中的信息传递到我网站上的隐藏表单字段中。
However, whenever I run a test, the code doesn't work - nothing gets pulled into my hidden field.但是,每当我运行测试时,代码都不起作用 - 没有任何东西被拉入我的隐藏字段。
Here is the code I am using (I have tried both javascript and jQuery - I'll show the code I've used for both):这是我正在使用的代码(我已经尝试过 javascript 和 jQuery - 我将展示我用于两者的代码):
document.querySelector("input[name='field:7961189']").value = "{{cookie - gclid}}";
$('input[name="field:7961189"]').val('{{cookie - gclid}}').change();
I've tried testing this out on my visible form fields by replacing the "name" with the one of my visible fields, like so,我已经尝试通过用我的可见字段之一替换“名称”来在我的可见表单字段上对此进行测试,就像这样,
document.querySelector("input[name='email']").value = "{{cookie - gclid}}";
$('input[name="phone"]').val('{{cookie - gclid}}').change();
and it works - the fields are populated with data from my cookie.它有效 - 这些字段填充了我的 cookie 中的数据。 But when I try the code at the top of the page, it doesn't work.但是当我尝试页面顶部的代码时,它不起作用。 I am stumped.我很难过。 Any help or pointers in the right direction would be much appreciated.任何正确方向的帮助或指示将不胜感激。
Here is the HTML around it.这是它周围的 HTML。
<div class="custom-form" data-form-id="1449777">
<h2 class="babel-ignore">UTM Fields</h2>
<p class="babel-ignore form-description">Disruptive Analytics UTM Fields</p>
<div class="form-group" data-field-id="7961189">
<label for="field:7961189" class="control-label babel-ignore">gclid </label>
<input type="text" class="text form-control" name="field:7961189" value="">
Try this:尝试这个:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
then然后
document.querySelector("input[name='field:7961189']").value = getCookie("gclid") // or wathever cookie is named
source: https://www.w3schools.com/js/js_cookies.asp来源: https://www.w3schools.com/js/js_cookies.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.