最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to bind a URL parameter with an input field in Vanilla JS? - Stack Overflow

programmeradmin1浏览0评论

I have an example running here, where the input is set by ?amount=123

const query = new URL(location).searchParams
const amount = parseFloat(query.get('amount'))

console.log("amount", amount)
document.getElementById('amount').value = amount
<label>
  Amount
  <input id="amount" type="number" name="amount">
</label>

I have an example running here, where the input is set by ?amount=123

const query = new URL(location).searchParams
const amount = parseFloat(query.get('amount'))

console.log("amount", amount)
document.getElementById('amount').value = amount
<label>
  Amount
  <input id="amount" type="number" name="amount">
</label>

Sorry, running the code snippet above or on JS fiddle doesn't appear to work with URL parameters.

If the input is changed, I want the URL to update too, with the new value. How do I achieve that in vanilla JS?

Share Improve this question edited Oct 25, 2020 at 7:55 Dan Knights 8,4084 gold badges27 silver badges54 bronze badges asked Oct 11, 2020 at 9:41 hendryhendry 10.9k23 gold badges94 silver badges156 bronze badges 3
  • you can simply use history API to change the URL – A.RAZIK Commented Oct 11, 2020 at 9:50
  • do you need it to reload the page too or just add it to the URL address and history or just alter the URL address without adding it to the history? – Saar Davidson Commented Oct 20, 2020 at 11:45
  • Is this your jsfiddle? jsfiddle/kaihendry/e67ywq8f/?amount=231 – react_or_angluar Commented Oct 24, 2020 at 2:48
Add a ment  | 

1 Answer 1

Reset to default 10 +100

You could add an input event listener and use window.history.replaceState:

const origin = window.location.origin;
const path = window.location.pathname;

input.addEventListener('input', () => {
    // Set the new 'amount' value
    query.set('amount', input.value);
    // Replace the history entry
    window.history.replaceState(
        null,
        '',
        origin + path + '?amount=' + query.get('amount')
    );
});
发布评论

评论列表(0)

  1. 暂无评论