1

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());
});
13
  • What is expected result? Commented Sep 29, 2017 at 16:57
  • @guest271314 it should be changing the URL to domain.com/?input_value=3&next_filter_value=2 etc. Commented Sep 29, 2017 at 16:58
  • Where does code call .replaceState()? Commented Sep 29, 2017 at 17:01
  • 1
    window.history.replaceState({}, "input_value", replaceQueryString(location.href, "input_value", $(this).val()))? Commented Sep 29, 2017 at 17:32
  • 1
    See developer.mozilla.org/en-US/docs/Web/API/History_API Commented Sep 29, 2017 at 17:36

1 Answer 1

1

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

window.history.replaceState({}
, "input_value"
, replaceQueryString(location.href, "input_value", $(this).val()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.