I will tell you why the use of Documnt.Ready() is a good practice in jQuery but before that I want to show you a small demo of code.
I will create a HTML page named "HtmlPage.html" with a TextBox like.
- <input id="Text1" type="text" />
Note
I am using the Visual Studio 2012 as the editor.
Download the jQuery library from the following links.
https://jquery.com/
Add the .js file in to the page as in the following:
- <script src="jquery-1.10.2.js"></script>;
Add the following jQuery code to the body tag after the TextBox that will add the text to the TextBox.
- <script type="text/javascript">
- ("#Text1").val("This is my textbox");
- </script>
And result will be look like:
But what will happen if I write the jQuery code before the TextBox as in the following?
- <body>
- <script type="text/javascript">
- $("#Text1").val("This is my textbox");
- </script>
- <input id="Text1" type="text" />
- </body>
As you can see in the following result there is no text set in the TextBox:
But the question is "Why the TextBox is blank this time".
Answer
jQuery didn't get the TextBox control, that's why the TextBox didn't set the value.
To understand why jQuery didn't get the TextBox control, you need to be familiar with execution of the Data Object Model (DOM).
“The data object model loads the code of the HTML page into memory line-by-line or sequentially, so it didn't understand the TextBox control when I wrote the code of jQuery to set the value of TextBox because the control was not yet loaded into memory.”
Solution
To resolve this situation always use the Documnt.Ready() function that will execute the code after the document is ready after loading.
- <body>
- <script type="text/javascript">
- $(document).ready(function () {
- $("#Text1").val("This is my textbox");
- });
- </script>
- <input id="Text1" type="text" />
- </body
Tip: Always write the JavaScript or jQuery code in a single place and especially in the head tag that will separate it from the body tag.