Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript onclick not working in jsfiddle

I am trying to make jsfiddle , my onclick is not working in jsfiddle. what is wrong in my code

<input value="press" type="button" onclick="myclick()">


function myclick(){
   alert("myclick")
}

http://jsfiddle.net/hiteshbhilai2010/gs6rehnx/11/

EDIT

I tried No wrap - In head and tried again with document.ready it is not working in jsfiddle again

ERROR - Uncaught ReferenceError: myclick is not defined 

http://jsfiddle.net/hiteshbhilai2010/33wLs160/6/

I have checked with already existing question here but my problem is happening when I am trying it in jsfiddle

Can some one please help me ....thanks

like image 633
Hitesh Avatar asked Oct 12 '14 20:10

Hitesh


2 Answers

You need to select No library (pure JS) and No wrap - in head. Then it will work as a simple HTML with javascript page.

This will be inserted in a <script> element in the <head>:

function myclick(){
  alert("myclick")
}

See demo

like image 57
dreyescat Avatar answered Nov 11 '22 01:11

dreyescat


As others said, for first case you have to set No wrap - in <head> or No wrap - in <body> as javascript panel settings (the blue link at js panel top-right).

For the second (your Edit) question, your code inside a function and the js will run it (within a new context), but it will do nothing as you just define a function and ignore it without any call or assignment.

if you call alert(myclick) you will see all the code is executed and its defined at that point. see this fiddle

$(document).ready(function() {

  //alert("ready is executed");

  function myclick(){
    alert("myclick is called")
    window.location.reload(true);
  }

  alert(myclick); //this will show the myclick is a defined function!

  //document.getElementsByTagName("input")[0].onclick = myclick;
})

if you call this:

document.getElementsByTagName("input")[0].onclick = myclick;

in that $(document).ready({...}) scope, it will be assigned to the button and works as you wish.

like image 33
S.Serpooshan Avatar answered Nov 10 '22 23:11

S.Serpooshan