JS DOM: Update URL Query String
Problem Description
if you have a Input Text Field such as a search box, and you want user to be able to use the URL to fetch the same search result they typed in the search box.
Solution
make your code do 2 things:
- when the page is loaded, get the search text from the URL parameter, fill it in the search box. (again, this is done only when the page loads.) Use
window.location.search - When search box is changed, such as user typed something, update the URL parameter. (use
window.history.pushState)
Get the URL Parameter Value
here's how to get the URL param values:
const searchBox_kqWNN = document.getElementById("searchBox_kqWNN"); { const xurlSearchStr = new URLSearchParams(window.location.search); if (xurlSearchStr) { (searchBox_kqWNN.value) = xurlSearchStr.get("q"); } }
Set the URL Parameter Value
here's how to get set URL param values, from a search box value:
const xurl: URL = new URL(window.location.toString()); xurl.searchParams.set("q", searchBox_kqWNN.value); window.history.pushState({}, "", xurl.toString());