0

I am learning javascript and i can't manage to make this work, an alert message should appear when i click the submit button

Html

<html>
<head>
    <title>Understanding the Document Object Model</title>
    <script type="javascript" src="script.js"></script>
</head>
<body>
    <h1 id="title">Understanding the Document Object Model</h1>
    <p id="first">This is the first paragraph</p>
    <p id="second"><strong>This is the second paragraph</strong></p>
    <p id="third">Third paragraph</p>
    <input type="submit" id="clickMe" value="Click Me"/>
</body>
</html>

Javascript script.js

window.onload=function(){
document.getElementById("clickMe").onclick=runTheExample;
}

function runTheExample(){
alert("running the example");
}
4
  • 3
    Submit buttons are supposed to be in a form. If it's just a button, then use a type button <input type="button" ...> or a button element: <button ...>...</button>. Commented Oct 21, 2015 at 13:24
  • 1
    Your code seems to work just fine: jsfiddle.net/jmLr5fyz Commented Oct 21, 2015 at 13:26
  • I also think it works ok codepen.io/anon/pen/MarZdO Commented Oct 21, 2015 at 13:28
  • @Saravana: which browsers would that be? Commented Oct 21, 2015 at 13:32

2 Answers 2

3

Your type attribute is wrong. It should be "text/javascript"

It works fine for me after making that change

==================================

EDIT:

As a note, my debugging process was to try invoking the alert() directly in the script. script.js became:

alert("running the example");

window.onload=function(){
    document.getElementById("clickMe").onclick=runTheExample;
}

function runTheExample(){
    alert("running the example");
}

That was triggering the alert either, which says that the whole script isn't in play. So it must be the invocation of the script that's the problem. Once you've determined that, there aren't many things left to check.

Sign up to request clarification or add additional context in comments.

1 Comment

Good catch. However, it would be even better to remove it completely. (Maybe you should also say which type attrribute)
1
<script type="text/javascript" src="script.js"></script>

You change your external javascript file link like this. Because,type attribute of script tag should come as text/javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.