Reputation: 73
Upon submitting a form I want to append to a URL the value from my input text field. So when the URL is http://localhost:8080/myfile.html?Filters=p1%3D"Hello" and then I submit to the text field p2="Bye" I want the URL to be http://localhost:8080/myfile.html?Filters=p1%3D"Hello"&Filters=p2%3D"Bye"
But for some reason when I press submit the desired URL appears for a second, but upon the page loading the URL becomes http://localhost:8080/myfile.html?Filters=p2%3D"Bye" I.e the first filter is overwritten. I don't know if it's something to do with clicking submit refreshing the page?
The purpose for this is basically I want to filter results from a list, and be able to add filters like p1="Hello" one by one through a input text box. Perhaps there's a better way of doing this.
HTML:
<form onsubmit="appendFilter()">
<label for="filters">Add filter:</label><br>
<input type=text id="filters" name="Filters" placeholder="Filter results..">
<input type="submit">
</form>
JavaScript:
function appendFilter() {
var filter = document.getElementById('filters').value
let searchParams = new URLSearchParams(window.location.search);
searchParams.append("Filters", filter)
window.history.replaceState({}, '', `${location.pathname}?${searchParams}`);
}
Upvotes: 0
Views: 785
Reputation:
What you're doing is not correct.
<form onSubmit={(e) => {e.preventDefault(); submit()}}>
// form things
</form>
...
const submit = () => {
// apply any logic here
fetch('https://example.com', {
method: 'post',
body: JSON.stringify({
// form values here
})
}
// or window.location.href= // params here
}
Upvotes: 1