I have two jQuery codes – http://jsfiddle.net/Lijo/CXGX7/7/ and http://jsfiddle.net/Lijo/CXGX7/8/ . The first code returns undefined whereas the second code returns text of button.
QUESTIONS
- What is the reason for this difference in result?
- Why is the first code not returning expected text of button?
Note: I verified that both are using same version of jQuery (by an alert of jQuery)
alert($.fn.jquery);
CODE
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.1.js"></script>
<script type="text/javascript">
alert($('.myButton').attr("value"));
</script>
</head>
<body>
<form method="post" action="Test.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE0MDM4MzYxMjNkZMycQvsYQ+GPFsQHoQ8j/8vEo2vQbqkhfgPc60kxXaQO" />
</div>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKqxqqrCgLi/JazDQKM54rGBqgaroRQTXJkD1LyUlVxAmLRCNfTGVe73swQBMemBtvN" />
</div>
<div>
<input name="txtEmpName" type="text" id="txtEmpName" />
<input type="submit" name="Button1" value="Submit" id="Button1" class="myButton" />
</div>
</form>
</body>
</html>
REFERENCES
That’s because in the first version, when your script executes, the button is probably not yet loaded in the DOM.
In this version, you are writing
alertdirectly in the html page. So, when that portion of the page is loaded in the browser, it will be executed immediately. At this point, the rest of your page is not loaded, so your$('.myButton')selector will return nothing (you can check it by$('.myButton').length).In this version, you are writing this code inside the
JavaScriptpanel of JsFiddle. The JS code that you write in here runs inside anonloadevent handler, which ensures that all of your html has been loaded before executing any JS code inside it.So, in the first version, your code is converted to something like this –
and for the second version –
Edit
The
$(document).ready()function is called whenever DOM is fully loaded in the browser. You pass a callback function as an argument to this function which will be called when it happens. Usually, anything you want to do with jQuery, you do it inside that callback. This is the very first thing to learn about jQuery. You can get an official tutorial about it here.This method is somewhat similar to window.onload, except that it fires as soon as your HTML document has been loaded, and
window.onloadis called after all the contents of a page(including images and other resources) has been fully loaded.