1

I'm currently trying to make a program in which you enter a link into an HTML form and when you click a button it sends you to that link. However, when I click the button the page just clears the form. I'm a Python native and a newbie to HTML/JS so the way I'm structuring my code may be why:

<form>
    <input type="url" id="link" placeholder="Enter link of website:" required>
    <br>
    <button class="outline" id="open">Create gate</button>
    </form>
    <script type="text/javascript">
        document.getElementById("open").onclick = () => 
        location.assign(String(document.getElementById("link").value));
    </script> </form>
Roho Carro
  • 13
  • 4
  • Add `type="button"` to your button. That will prevent the form from automatically submitting. – Andy Nov 24 '21 at 05:43
  • Thanks. Can submit your comment as an answer so I can mark it as correct? – Roho Carro Nov 24 '21 at 05:46
  • As you can see from the duplicate question _how_ the buttons are determined to be submit buttons is generally browser-based - there seems to be no standard. That said, that question was written in '09 so things may have changed. But if you explicitly say your button isn't of `type="submit"` the form won't submit if you click on it. – Andy Nov 24 '21 at 05:55

2 Answers2

1

Since, you are using a form. Your Button

<button class="outline" id="open">Create gate</button>

is acting as the form submit button and hence it refreshes the page before executing the location.assign() method. There are many ways to fix this.

  1. One simple way is to exclusively tell the browser that this button is not the submit button, we can do that by using type="button" attribute in our button.

    Create gate

  2. You can use e.preventDefault() on your form submit to stop refreshing of the page.

Try the below code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Location Object</title>
</head>
<body>
    <form>
        <input type="url" id="link" placeholder="Enter link of website:" required>
        <br>
        <button class="outline" id="open">Create gate</button>
    </form>
    <script type="text/javascript">
        document.getElementById("open").addEventListener('click', (e) => {
             e.preventDefault();
            location.assign(String(document.getElementById("link").value));
        });
       
    </script>
    </form>
</body>
</html>
Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
0

Your code, exactly as provided, pasted into a minimal HTML5 boilerplate template, works in the Textastic code editor and in Safari running on localhost.

Perhaps some other JavaScript in the vicinity of your event listener is breaking the arrow function. Maybe bracketing the one function statement could help?