I’m new to JavaScript and jQuery. I want to click a button and have a js function executed. (For this example, it’s just an alert, but it’s actually an ajax function.)
The first alert appears, but after I click the button, I never see the second ("did it") alert. It looks like JavaScript doesn’t think the doIt() function is defined when the button is clicked.
Here’s the relevant code:
$(document).ready(function()
{
alert('ready');
function doIt() {
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
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 yourdocument.ready(so it’s not scoped exclusively to that closure), or (a better approach IMO) bind it inside thedocument.ready, here’s what I mean by each:Binding it inside (remove your
onclick=""for this):or the anonymous version (again remove your
onclick=""):Or move it outside (keep your
onclick=""):