Search code examples
javascriptjsfiddle

Simple click event not working in JS


I have created a very simple fiddle in JsFiddle. To my surprise it is not working. Please let me know if I am mistaking anything.

HTML-

<button onclick="test1()">
Push
</button>
<input type="button" value="Click" onclick="test1()"/>

JS-

function test1(){
    alert("1");
}

I want to show a simple alert on button click but it is not showing up.

Please click here to see this simple fiddle.


Solution

  • If you take a look at your browsers web console you can see an Uncaught ReferenceError is thrown. It tells you that function test1 is not defined.

    In this answer the same error is discussed. The problem is, that the javascript file is linked into the html header and called before the html code is initialized. The answer suggest to use jquery and its corresponding ready function.

    If you want to do plain javascript you can solve this issue by directly embedding your code into your html using a script tag.

    Take a look at the following snippet.

    <button onclick="test1()">
    Push
    </button>
    <input type="button" value="Click" onclick="test1()"/>
    <script>
    function test1(){
    	alert("1");
    }
    </script>