6

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?

Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49
hendry
  • 9,725
  • 18
  • 81
  • 139

1 Answers1

10

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')
    );
});
Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49
  • Building the url by concatenating strings like this: `origin + path + '?amount=' + query.get('amount')` ... is this best practice? – hendry Oct 18 '20 at 03:25
  • It only alters the `amount` query and maintains the original URL, so, I'd say so. – Daniel_Knights Oct 18 '20 at 04:40
  • Using full (absolute) URL might be reasonable precaution for untested browsers, but from what I've tried using just the (relative) `'?search'` fragment instead works the same. (Looking at specs I think it should work this way, because base should be the implied from `window.location`, but I'm not sure I understand it correctly; https://html.spec.whatwg.org/multipage/history.html#dom-history-replacestate ) – myf Oct 30 '20 at 23:37