0

How do I activate a javascript button as if a user clicked it? Could I run javascript code to activate the button? (supposing I did not already know the code in the button, and I am on a random website where I can not change existing code)

<!DOCTYPE html>
<html>
  <body>
    <form action="aaa.php">
      <input type="text" />
      <input id="button" type="submit" />
    </form>
    <script>
      var btn = document.getElementById("button");
      //is there anything like: btn.click?
    </script>
  </body>
</html>
luek baja
  • 1,475
  • 8
  • 20
  • The syntax of the inline handler is invalid. If that's really the HTML markup you have, you can't run it as-is - it needs to be fixed first. But even still, [don't use inline handlers](https://stackoverflow.com/a/59539045), they have a demented scope chain, require global pollution, and have quote escaping issues. Use `addEventListener` instead – CertainPerformance Apr 01 '20 at 20:14
  • 5
    `document.getElelementById("button").click();` – Scott Marcus Apr 01 '20 at 20:14
  • A `;` is missing after your alert. – Roberto Caboni Apr 01 '20 at 20:21
  • @RobertoCaboni While I agree that one should not rely on automatic semicolon insertion, the fact that it's not added here is not an error, nor related to the question or answer. – Scott Marcus Apr 01 '20 at 20:28

3 Answers3

2

<!DOCTYPE html>
<html>
  <button id="button"onclick="myFunction()">b</button>
  <!--creates the button-->
  <script>
    var btn = document.getElementById("button");
    btn.click();
    
    function myFunction(){
       alert('working');
       }
  </script>
</html>
DCR
  • 14,737
  • 12
  • 52
  • 115
-1

Here's one way you can handle it, call a specific function from your onClick

<!DOCTYPE html>
<html>
  <button id="button" onclick="clickButton()">b</button>
  <!--creates the button-->
  <script>
    function clickButton() {
       alert("hello!");
    }

  </script>
</html>

To answer your question more directly, this is one way you can do it

document.getElementById('button').onclick=function(){/* some code */}
DSmith
  • 9
  • 2
-1

As mentioned, You can separate out HTML and javascript.

Sample.

<!DOCTYPE html>
<html>

<body>
    <button id="button">Click Here</button>
    <button onclick="onClickBtn(this)">Click Here 2</button>
    <!--creates the button-->
    <script>
        var btn = document.getElementById("button");
        btn.addEventListener("click", (event) => {
            alert("Hi")
        })
        function onClickBtn(event) {
            alert("Btn 2")
        }
    </script>
</body>
</html>
xdeepakv
  • 7,835
  • 2
  • 22
  • 32