Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a URL parameter with an input field in Vanilla JS?

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?

like image 910
hendry Avatar asked Oct 11 '20 09:10

hendry


1 Answers

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')
    );
});
like image 85
Daniel_Knights Avatar answered Nov 09 '22 22:11

Daniel_Knights