HTML and CSS Reference
In-Depth Information
invoking Javascript on Page Load
Another approach is to put the <script> tag and JavaScript function in the <head> of the document
and then invoke or call the function when the page is loaded. This method allows all the JavaScript
call
functions to be grouped in one central location which, in turn, makes it easier to debug and fine-tune.
Take a look at a slightly more elaborate JavaScript function that returns the date in a familiar for-
mat. This function, getTodaysDate() , establishes a new date object ( theDate ) and then extracts
specific details from it in numeric format: month, day, and year. Next it puts them all together and
stores that text string in another variable, theFullDate . Finally, it sets a form field on the page to
theFullDate variable. Here's the code in its entirety:
<script type=”text/javascript”>
<!--
function getTodaysDate() {
var theDate = new Date();
var theMonth = theDate.getMonth() + 1;
var theDay = theDate.getDate();
var theYear = theDate.getFullYear();
var theFullDate = theMonth + “/” + theDay + “/” + theYear;
document.theForm.todaysDate.value = theFullDate;
}
//-->
</script>
All the JavaScript statements look pretty straightforward, although you may be
wondering about the code that gets the value for the current month — why is there
a plus 1? JavaScript, in true programmer's fashion, starts counting months with 0,
so to get a value that makes sense to non-programmers you need to add a 1.
To get the date on the page, you need two things: an input field named todaysDate in a form named
theForm and a way to call the JavaScript function. The form field is used because it's very easy for
theForm
JavaScript to change the value of a text field. To activate the function, use what is known as an event
handler , placed in the
<body> tag, like this:
<body onload=”getTodaysDate();”>
When the page loads, the function is called and the current date is placed in the text form control,
shown in Figure 21-3. Why doesn't it look like a text field? Why, the magic of HTML and CSS of
course! In the HTML code, I added a disabled attribute like the following to the <input> tag so
that users would not be able to click into the text field:
<input type=”text” name=”todaysDate” id=”todaysDate” disabled=”disabled” />
Search WWH ::




Custom Search