0

I have a dropdown on my website, where users can select different site-names. Next to the dropdown I have a submit button.

I would like users to select a site-name, from the dropdown, and when they click on submit they should be redirected to a specific url, with the dropdown value appended.

<form id="form" method="get">
   <option value="1">Website Name 1</option>
   <option value="2">Website Name 2</option>
   <option value="3">Website Name 3</option>

   <button class="btn" type="submit">GO!</button>
</form>

Example case:

  • Users selects "Website Name 2"
  • User clicks "GO!" button
  • Site opens a new window with target "https://example.com/site/2"

2 Answers 2

1

There are many ways to do this. However you can try below way. In the dropdown value add a complete url which you want to redirect to instead of just value and on button click redirect to that site.

Make sure button type is not 'submit' and attach a click event with a javascript funtion. In the javascript function read the selected value from the dropdown and use

window.location.href

to redirect to that site.

function redirect() {
  var value = document.getElementById("site").value;
  window.location.href = value;
  return ;
}
<form id="form" >
<select name="site" id ="site">
   <option value="https://Google.com/1">Google</option>
   <option value="https://stackoverflow.com/2">StackOverflow</option>
</select>
   <button class="btn" type="button" onclick="redirect()">GO!</button>
</form>

Sign up to request clarification or add additional context in comments.

Comments

1

There are multiple ways to accomplish this functionality. I prefer having minimal HTML and handling everything in the JavaScript. We will be using an EventListener to accomplish this in my example.

Change your HTML to this:

<form id="form" method="get">
  <select id="selection">
     <option value="1">Website Name 1</option>
     <option value="2">Website Name 2</option>
     <option value="3">Website Name 3</option>
  </select>
   <button class="btn" type="submit">GO!</button>
</form>

Then you can use simple JavaScript to accomplish what you want:

let url = "https://example.com/site/";

document.getElementById('form').addEventListener('submit', (e) => {
    e.preventDefault();
  let selection = document.getElementById('selection').value;
  console.log(url + selection);
  window.location.href = url + selection;
});

This answer assumes that all URLs follow the https://example.com/site/1 format. If not, you can change the value in the option tags to be the actual URL and remove the URL prefix from the JavaScript.

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.