0

I need to update a URL parameter on a drop down change event with jquery. I got this code that works well when I got a single parameter in the URL, but when I got many parameters, the country in this case, will be deleted.

Here the code:

$('#state-input').change(function () {

      var hrefElement = $("#municipality-input");
      var href = hrefElement.data('autocomplete-url');

      href = href.replace(/(stateId=)[A-Z].+/ig, '$1' + $(this).val());
      hrefElement.attr('data-autocomplete-url', href);
});

The URL on page load:

data-autocomplete-url="/SKU/GetCities?stateId=QC&countryId=CA"

On the change event

data-autocomplete-url="/SKU/GetCities?stateId=NB"

What I want :

data-autocomplete-url="/SKU/GetCities?stateId=NB&countryId=CA"

Is there any way to keep the country with a little changes of the code I got?

Thanks

David Létourneau
  • 1,250
  • 2
  • 19
  • 39

1 Answers1

1

You forget the second part when replacing the regex. Maybe you need to do this:

href = href.replace(/(stateId=)[A-Z]+(.*)/ig, '$1' + $(this).val() + '$2');

So the result will be:

$('#state-input').change(function () {

      var hrefElement = $("#municipality-input");
      var href = hrefElement.data('autocomplete-url');

      href = href.replace(/(stateId=)[A-Z]+(.*)/ig, '$1' + $(this).val() + '$2');
      hrefElement.attr('data-autocomplete-url', href);
});