[英]Filling a form field with the current URL via javascript
我正在尝试在我使用页面的当前 URL(包括所有 UTM 标记)创建的表单中填充隐藏字段。
我在尝试将 URL 的值输入该字段时似乎遇到了麻烦,由于某种原因它一直报告 null
var urlnew = window.location.href;
document.querySelector("input[name='url_hidden']").value = "urlnew";
如果我硬编码一个值,它可以正常工作并提交,但它只是我尝试使用其他东西的任何时候
您应该删除引号:
<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>
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}`); }
<form onsubmit="submitForm(event)"> Username: <input type="text" name="username" id="username" placeholder="Username"> <br> Password: <input type="password" name="user_password" id="user_password" placeholder="Password"> <br> Hidden URL: <input type="hidden" name="hidden_url" id="hidden_url"> <br> <button type="submit">Submit</button> </form>
您可能还想填充 value 属性:
document.querySelector("input[name='url_hidden']").value = urlnew;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.