Search code examples
htmllisthyperlinksubmit

How to select from list and click submit button then go to link "in HTML"


I found this code for my project. I want to change this to open website with click on submit button

<html>
<body>
<form action="/action_page.php" method="get">
  <label for="cars">Choose a Site:</label>
  <select id="site" name="site">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
  <input type="submit">
</form>
</body>
</html>

for example: when select "Google" from list, with click on "submit" button open "www.google.com" that exist on "action_page.php"

I dont have "action_page.php" code


Solution

  • Firstly, I modified your html code:

    <html>
    <body>
    <form method="get">
      <label for="cars">Choose a Site:</label>
      <select id="site" name="site">
        <option value="Google">Google</option>
        <option value="Yahoo">Yahoo</option>
        <option value="MSN">MSN</option>
      </select>
    </form>
    <button type="button" id="button" >Submit</button>
    
    <script src="script1.js"></script>
    </body>
    </html>
    

    Made a button outside of the form and referenced the external js file script1.js

    Then I created the js file and added this code to it:

    var select = document.getElementById('site');
    
    document.getElementById("button").onclick = function(){
        var value = select.value
        if (value == "Google")
        {
            window.location.href = "https://www.google.com/";
        }
        else if (value == "Yahoo")
        {
            window.location.href = "https://www.yahoo.com/";
        }
        else if (value == "MSN")
        {
            window.location.href = "https://www.msn.com/";
        }
    };
    

    It finds the select tag and the button from the html script, checks if the button was pressed and redirects to the corresponding website based on the dropdown selection.