That is because the code that works and the code that doesn't work are not equal. They have different events in which they would trigger. For example, the first piece of code,
alert('it worked');
Would not need any event to happen, in order to alert the user. It would execute as soon as browser hits the line of code. But, the other cases have an event that needs them to trigger. Perhaps you are novice to jQuery?
$('#btnSubmit').click(function() {
alert('it works too');
});
But the above code to work requires that
you actually click on that button. Also, you need to close the brackets, why did you leave the door open?
Those lines of code that are under the
events in jQuery[
^], do not execute (same as JavaScript;
the event functions are executed once that event takes place). To execute them,
you need to perform the event (on the same element).
Also, you may not understand what a
$(document).ready(function() { })
handler is. It is a function, that executes once the document object in jQuery is ready. Then the function to execute is where you write the code, the code then attaches the jQuery function handlers to jQuery objects.
var obj = document.getElementById("elId");
var jObj = $('#elId');
They have different functions on them, based on the object type. I would recommend that you learn more about
.ready()
[
^] function. Same applies to
$(window).load(function () { })
, read their documentations.
Edit
As from your edit, it seems as if the problem was closing brackets. Try this,
$(document).ready(function () {
$("#btnSubmit").click(function () {
alert("it worked");
});
});
This should work, if
you click on the button with that ID.