-2

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.

5
  • 3
    onclick not onclcik Commented Mar 29, 2017 at 11:51
  • 1
    correct the typo Commented Mar 29, 2017 at 11:52
  • 1
    It doesn't work even after correcting typo. Commented Mar 29, 2017 at 11:54
  • It works fine for me. Where is your JS located? Check the console output. Commented Mar 29, 2017 at 11:59
  • Console says test1 is undefined. I am using JsFiddle. Commented Mar 29, 2017 at 12:01

2 Answers 2

2

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>

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

Comments

0

Write the function inside the script tag as shown in this jsfiddle.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.