首页 > 解决方案 > 将当前页面 URL 作为隐藏字段提交,同一页面上有多个表单(Javascript)

问题描述

我在一个网站上设置了一些表单,其中同一个表单会在一个页面上出现多次(这就是我不能getElementById在这里使用的原因)。

我已经尝试了所有可以找到的方法来获取当前 URL 作为隐藏字段传递,但我无法弄清楚。感谢您的任何帮助!

HTML

<form>
    <input type="email" name="email-address" placeholder="Your work email" />
    <input type="button" class="btn btn-inline" value="Submit info" />
    <input type="hidden" name="convertURL" value="" />
</form>

当前脚本

<script>
    document.getElementsByName("convertURL").value = window.location.href;
</script>

表单提交脚本

如果它有帮助,这就是表单的提交方式:

<script>
$('input[type="button"]').click(function(e){
    e.preventDefault();
    $.ajax({
        url:'https://examplesite.com/',
        type:'post',
        data:$(this.form).serialize(),
        success:function(){
          window.location = "/success";
        }
    });
});</script>

标签: javascripthtmlformsdom

解决方案


如果您使用的是 jquery,这将解决它。

$('[name=convertURL]').val(window.location.href);

推荐阅读