Home > Back-end >  Is it possible to do <select> with links opening after clicking submit?
Is it possible to do <select> with links opening after clicking submit?

Time:03-03

Is it even possible to do select with links that when you click submit button it will move you to the selected website, for example

<form>

    <select>
            <option value="1" id="1"> test 1 </option>
            <option value="http://www.google.com" id="http://www.google.com"> google.com </option>
            <option value="http://www.youtube.com" id="http://www.youtube.com"> youtube.com </option>
            <option value="http://www.facebook.com" id="http://www.facebook.com"> facebook.com </option>    
        </select>

        <input type="submit">
//when submit clicked, and you choosed any option then you will be moved to this website
</form>

CodePudding user response:

Using a bit of javascript you could add a change handler to the select that navigates the user to the value of the selected option.

Note that this may not work within the stackoverflow demo frame, but should be fine on your site.

document.querySelector('select').addEventListener('change', (e) => {
  document.location.href = e.target.value;
});
<select>
  <option value="1" id="1"> test 1 </option>
  <option value="https://www.google.com" id="http://www.google.com"> google.com </option>
  <option value="https://www.youtube.com" id="http://www.youtube.com"> youtube.com </option>
  <option value="https://www.facebook.com" id="http://www.facebook.com"> facebook.com </option>
</select>

CodePudding user response:

Yes, it possible to have a <select> element with links opening after clicking submit.

In order to do so, add the following JavaScript code:

const submitButton = document.querySelector("[type=submit]")
const select = document.querySelector("select")

submitButton.addEventListener("click", function (e) {
  e.preventDefault()

  window.location.href = select.value
})
  •  Tags:  
  • html
  • Related