Search code examples
inputhyperlinkhrefdropdownonchange

Change link href depending on drop-down value


I have a button witha a href link:

<a href="mysite.com/filter">My button</a>

Then I have 3 drop-down (select) inputs, lets call them A, B & C enter image description here

Depending on what the users choose, I want the link to be changed as this

<a href="mysite.com/filter-A-B-C">My button</a>

All three drop-downs will be Required


Solution

  • Find the following snippet useful. Handle the default values for the query params.

    <select id="a" onchange="changeUrl()">
      <option value="a1">a1</option>
       <option value="a2">a2</option>
    </select>
    
    <select id="b" onchange="changeUrl()">
      <option value="b1">b1</option>
       <option value="b2">b2</option>
    </select>
    
    <select id="c" onchange="changeUrl()">
      <option value="c1">c1</option>
       <option value="c2">c2</option>
    </select>
    
     <a id="test" href="mysite.com">My button</a>
      <script>
      function changeUrl(){
      let url="mysite.com?a=";
      let a= document.getElementById('a').value;
      url+=a+"&b=";
      let b=document.getElementById('b').value;
      url+=b+"&c=";
      let c=document.getElementById('c').value;
      url+=c;
      document.getElementById('test').href=url;
      }
      </script>
    </body>