使用Jquery将字段输入值作为查询字符串附加到url

Use Jquery to append a field input value to the url as a query string

本文关键字:字符串 查询 url Jquery 字段 输入 使用      更新时间:2023-09-26

我相信我有大部分权利,但可能会打乱顺序,并且由于某种原因无法得到一个小提琴来保存。基本上,我需要抓取表单输入的一部分,并将其追加为提交上的查询字符串,以便在下一页上触发附属cookie。所有代码都以AAA-11值开头,然后是实际的附属参考代码。所以

<form>
    <label>Affiliate Code</label>   
    <input type="text" id="code">
    <input type="submit" id="submit_btn">        
</form>

和JS:

$('#submit_btn').on('click', function() {
    var str = $('#code').val();
    var acode = str.substr(6);
    location.href = location.href + "?ref=" + acode;
});

我在这里错过了什么?

您的按钮正在提交表单,因为它的属性type="submit"

您可以将属性更改为type="button",或者使用 event.preventDefault() 编程阻止表单提交,以便您可以修改数据。

$('#submit_btn').on('click', function(event) {
    event.preventDefault();
    var str = $('#code').val();
    var acode = str.substr(6);
    location.href = location.href + "?ref=" + acode;
});

[编辑](评论)

如果您需要修改表单action并提交表单,请使用以下命令:

$('#submit_btn').on('click', function(event) {
    event.preventDefault();
    var str = $('#code').val();
    var acode = str.substr(6);
    // change form action attribute and submit the form:
    $(this).closest('form').attr('action', location.href + "?ref=" + acode).submit();
});