Why can’t I use onClick to execute a function inside a jQuery $(document).ready function?

It’s because that function isn’t in a global context, which is where your onclick="" is looking for it. You need to move it outside your document.ready (so it’s not scoped exclusively to that closure), or (a better approach IMO) bind it inside the document.ready, here’s what I mean by each:


Binding it inside (remove your onclick="" for this):

$(document).ready(function() { 
  alert('ready');
  $("input[name="Go"]").click(doIt);
  function doIt() {
    alert('did it');
  }
});

or the anonymous version (again remove your onclick=""):

$(document).ready(function() { 
  alert('ready');
  $("input[name="Go"]").click(function() {
    alert('did it');
  });
});

Or move it outside (keep your onclick=""):

$(document).ready(function() { 
  alert('ready');
});
function doIt() {
  alert('did it');
}

Leave a Comment