通过 javascript 使用当前 URL 填充表单字段

时间:2021-04-22 17:12:11

标签: javascript

我正在尝试使用包含所有 UTM 标签的页面当前 URL 创建的表单中填充隐藏字段。

我在尝试将 URL 的值放入该字段时似乎遇到了问题,由于某种原因它一直报告为 null

var urlnew = window.location.href;
document.querySelector("input[name='url_hidden']").value = "urlnew";

如果我硬编码一个值,它可以正常工作并提交,但只是在我尝试使用其他东西的时候

2 个答案:

答案 0 :(得分:0)

您应该删除引用:

<html>
<body>
  <input type=text name=url_hidden>
</body>
<script type="text/javascript">
    var urlnew = window.location.href;
    document.querySelector("input[name='url_hidden']").value = urlnew;
</script>
</html>

答案 1 :(得分:0)

object
function submitForm(e) {
  e.preventDefault();

  const username_el = document.querySelector("input[name='username']");
  const password_el = document.querySelector("input[name='user_password']");
  const hidden_el = document.querySelector("input[name='hidden_url']");
  
  const url = window.location.href;
  
  hidden_el.value = url;
  
  window.alert(`${username_el.value} - ${password_el.value} - ${hidden_el.value}`);
}

相关问题