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?
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')
);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With