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
1 Answer
Reset to default 10 +100You 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')
);
});