Search code examples
javascripthtmlforms

Option should leads to URL only when submit button is clicked


I have made a dropdown form with two options, each lead to different URL. I want the selected option lead to its 'URL' ONLY when the submit button is clicked. I have used the following JS code:

function handleFormSubmit() {
 var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
var destination = document.getElementById("destination");
location = destination.options[destination.selectedIndex].value;
});
}

Now, when I click the submit button, it does not navigate to the url specified in value attribute of option. (Nothing happens.)

Following is the HTML of my form:

`<form action="" method="post">
  <label for="destination">Travelling to:</label>
  <select id="destination" name="destination">
    <option value="https://nstcprep.blogspot.com/">Destination 1</option>
    <option value="https://nstcprep.blogspot.com/">Destination 2</option>
  </select>
  <input type="submit" value="Submit">
 </form>`

Solution

  • Just change the below code in your file.

    function link() {
                var dropDownVal = document.getElementById('destination').value;
                window.location = dropDownVal;
            }
    <form action="" method="post">
                <label for="destination">Travelling to:</label>
                <select id="destination" name="destination">
                    <option value="https://nstcprep.blogspot.com/">Destination 1</option>
                    <option value="https://nstcprep.blogspot.com/">Destination 2</option>
                </select>
                <button type="button" onclick="link();">Submit</button>
            </form>

    Let me know if this work.

    if you want to open in new tab just change this.

    window.open(dropDownVal, '_blank');