Babiker
Babiker

Reputation: 18818

JavaScript event not being fired

Once #theButton is clicked, an alert should be triggered. Why aren't any of the events being triggered using the following methods?

            var theButton = document.getElementById("theButton");
       
            theButton.onclick = function(){alert("Clicked!");}
            theButton.onclick = clickAlert;
            theButton.onclick(alert("Clicked!"));
    
            function clickAlert(){
                alert("Clicked!");
            }
        </script>
    </head>
    <body>
        <input type="button" id="theButton">
    </body>
</html>

Upvotes: 0

Views: 274

Answers (5)

T.T.T.
T.T.T.

Reputation: 34623

It works if you put the onclick within the input tag (and spell things right):

<html>
     <head>
      <script type="text/javascript" language="javascript">



       function clickAlert(){
        alert("Clicked!");       

       }

      </script>
     </head>
     <body>
      <input type="button" id="theButton" NAME="theButton" onclick="clickAlert()">
     </body>
    </html>

Upvotes: 1

Seattle Leonard
Seattle Leonard

Reputation: 6776

I like the jQuery.ready() answer, but I believe you could also move the <script> block to some point afeter you delcalre the button like at the end of the page.

Upvotes: 1

Peter Bailey
Peter Bailey

Reputation: 105914

You have three problems

  1. You misspell function on line 7. (This generates a runtime error, by the way)
  2. You try to access the node #theButton before it's available in the DOM. Take Pekka's advice for this one
  3. You overwrite the onclick property on line 8 - not sure if you're doing that on purpose or what

Upvotes: 2

Brandon
Brandon

Reputation: 85

Try wrapping it in the document.Ready() function.

Upvotes: 1

Pekka
Pekka

Reputation: 449783

Because theButton doesn't exist yet when you run your script?

Wrap it into the body's onload event or jQuery's ready().

Upvotes: 1

Related Questions