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>
The fix is easy enough, simply bind the OnClick event to the parent of the elements you want to be able to click on. That way, if the element you want to click on is removed and re-appended, the handler will still be there listening as the parent was never removed.
Yes, you can.
$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.
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');
}
You define doIt in your document.ready as a function statement.
Either you should use a function expression or declare the function out of the ready function.
$(document).ready(function()
{
alert('ready');
doIt = function() { //now has global scope.
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
(yes, the onClick is not really the jQuery way of doing it and probably should be replaced by a click handler defined in the ready function, but it works and is allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With