scopeak
scopeak

Reputation: 545

How to modify URL Query String without reload

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

Answers (1)

guest271314
guest271314

Reputation: 1

Pass replaceQueryString() function to third parameter of .replaceState()

window.history.replaceState({}
, "input_value"
, replaceQueryString(location.href, "input_value", $(this).val()));

Upvotes: 1

Related Questions