javascripthtmllocation-href

javascript window.location.href keeps adding to url


I have a simple dropdown that forwards to a new url onChange.

It looks like this:

function changeCompanyType(companyType) {
      window.location.href = 'type/'+companyType+'/';

    }

The first change works great and goes to the url:

http://127.0.0.1/companies/type/bank/

The next time I click on the dropdown from the new page it adds type and the company type again:

http://127.0.0.1/companies/type/bank/type/hosptial/

How can I just have the company type changed so the url doesn't keep being added to?


Solution

  • Prefix with a forward slash (/)

    window.location.href = '/type/'+companyType+'/';
                            ^ -- a slash to make an absolute url
    
    // or (depends on what you want to do)
    window.location.href = '/companies/type/'+companyType+'/';
                            ^ -- a slash to make an absolute url