Reputation: 545
I'm using the following method to change the query URL parameter corresponding to the input/dropdown on a form. Currently window.location.href
will cause a page reload on change. How can I integrate history.replaceState()
instead to modify the URL without reloading?
REGEX function
function replaceQueryString(url, param, value) {
var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
if (url.match(re))
return url.replace(re, '$1' + param + "=" + value + '$2');
else
return url + '&' + param + "=" + value;
}
On input change
$("#input_field").on('change', function(e) {
window.location.href = replaceQueryString(window.location.href, 'input_value', $(this).val());
});
Update
I've now managed to update the URL to the value domain.com/2
on change, but how can I run it through the replaceQueryString
function to parse it into domain.com/?input_value=2
$("#input_field").on('change', function(e) {
window.history.replaceState("#input_field", "input_value", $(this).val());
});
Upvotes: 1
Views: 4424
Reputation: 1
Pass replaceQueryString()
function to third parameter of .replaceState()
window.history.replaceState({}
, "input_value"
, replaceQueryString(location.href, "input_value", $(this).val()));
Upvotes: 1