0% found this document useful (0 votes)
58 views

Cs 952 Database and Web Systems Development: Lecture 6: Javascript

The document discusses JavaScript and its use in dynamic web page development. It provides an overview of JavaScript, how it can manipulate HTML elements and access properties of the DOM tree. It also covers embedding JavaScript in HTML, handling events, validating forms, and common JavaScript data types and operators.

Uploaded by

Kareem Nabil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Cs 952 Database and Web Systems Development: Lecture 6: Javascript

The document discusses JavaScript and its use in dynamic web page development. It provides an overview of JavaScript, how it can manipulate HTML elements and access properties of the DOM tree. It also covers embedding JavaScript in HTML, handling events, validating forms, and common JavaScript data types and operators.

Uploaded by

Kareem Nabil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

CS 952 Database and Web

Systems Development

Lecture 6: JavaScript
Structure of the course

1. HTML - Overview and forms


2. PHP - Form handling & Database linkage
3. CSS - Stylish pages
4. JavaScript - Form handling
5. Accessibility and Security

2
Business 3-tier architecture

HTML
CSS

Javascript

PHP

MySQL

3
JavaScript Overview (1)
• JavaScript can be used to make HTML pages more dynamic
– It can access and manipulate Web page components
• JavaScript supports graphic effects and helps toward intelligent Web
pages
• Intelligent Web pages can verify input, perform calculations, and
make presentation decisions based upon the results
• JavaScript is a light weight programming language and is embedded
directly into the HTML code
• JavaScript was influenced by many languages, especially Java

4
JavaScript Overview (2)
• JavaScript can read and write HTML elements
– It can be used to change HTML content, HTML attributes and
HTML styles
• You can use JavaScript to detect the visitor’s browser
type and load the appropriate page for that browser
• Cookies can be created using JavaScript
• Other features such as user validation and
authentication can also be handled through JavaScript

5
Document components
• HTML tags create document objects
• JavaScript lets you manipulate those objects
• For example, you use the HTML <body>
and </body> tags to create a Web page, or
document
• Once that document is created, you can
interact with it by using JavaScript which will
be interpreted by the user’s browser
6
HTML Document Object Model (DOM)

• When a web page is loaded, the browser creates a document


object model (DOM) of that page
• The DOM is a W3C standard
– It defines HTML elements as objects , properties (values) of
those elements, methods (actions) to access those elements
– E.g. innerHTML (property), getElementById (method)
• All HTML elements, as well as their content text and
attributes, can be accessed with JavaScript through the DOM
• The contents can be accessed, modified or deleted, and new
elements can be created
• The HTML DOM is platform and language independent

7
The DOM Tree
• The DOM presents an HTML document as
a tree-structure (a node tree), with
elements, attributes, and text
Some of the available elements
are document specific

8
Embedding JavaScript
• There are two ways to embed JavaScript code in an
HTML file
• Use the <script> and </script> tags to place
JavaScript code directly into an HTML file
– Either in the <head> or the <body> sections or both
• Use the <script> and </script> tags to include a
separate external JavaScript file within the HTML
– The external file will contain only JavaScript statements and
have a .js extension

9
‘Internal’
<html>
<head>
<script >
// JavaScript statements go here
function processOrder() {
// more JavaScript statements go here
}
</script>
</head>
<body>
<form name="myForm">
<input type="button" name="process" value="Click here to process your order"
onClick="processOrder();">

</form>
</body>
</html>

10
‘External’
<head>
<script src="myscript.js">
</script>
</head>
<body>
<a href="javascript:processOrder();">Click
here to process your order.</a>
...
</body>
</html>

11
JavaScript
• The syntax and language is similar to PHP
– Variables (dynamically typed)
• Number, string, Boolean, null, arrays, function, objects
– Operators
• Arithmetic, assignment, comparison, logical, conditional
– Conditions and loops
• if ... else if ... else and switch
• for and for/in loops
• while and do … while loops
String Operators
• + or += can be used to concatenate strings
txt1 = "What a very";
txt2 = "nice day";
txt3 = txt1 + " " + txt2;

txt1 = "What a very ";


txt1 += "nice day";
• Adding a number and a string will return a string
x = 5 + 5;
y = "5" + 5;
z= "Hello" + 5;
JavaScript Output
• JavaScript can "display" data in different ways
– Writing into an alert box, using window.alert()
– Writing into the HTML output using document.write()
– Writing into an HTML element, using innerHTML
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
– Writing into the browser console, using console.log()
Getting the time
• A common use for JavaScript is to display the
current time
• Always takes time from Web browser’s local
system
• Easily converted to UTC
– Co-ordinated Universal Time
– Equivalent to GMT

15
Getting the time (2)
• Store current date in a variable:
var now = new Date();
• The date is stored as the number of
milliseconds since January 1st 1970
• We need to convert this to a useful form:
localtime = now.toString();
utctime = now.toGMTString();

16
Displaying the time

• Display the values of a variable using


document.write statements:
document.write("<b>Local time:</b> " + localtime +
"<br>");
document.write("<b>UTC time:</b> " + utctime);

17
18
19
Event handlers
• Event handlers are built-in scripts that respond
to specific browser events
– e.g. mouse clicks, mouseover, on page load, etc.
– onabort, onblur, onchange, onclick, ondblclick,
ondragdrop, onerror, onfocus, onkeydown,
onkeypress, onkeyup, onload, onmousedown,
onmousemove, onmouseout, onmouseover,
onmouseup, onreset, onselect, onsubmit, onunload

20
Event handler - HTML file

21
Event handler – Browser display

Once OK is clicked,
the URL is loaded

22
Client-Side Processing of HTML Forms

• JavaScript provides two useful features to


HTML forms
– It lets you examine and validate user input
instantly right on the client
– It lets you give users instant feedback
Submission Example

24
Submission Example 2

25
Email Validation
<body>
<form name="getemail"; onsubmit="return check(this)";>
<p>Enter your e-mail address:
<input name="myemail" type="text"/></p>
<p><input type="reset" value="Reset">
<input type="submit" value="Submit"></p>
</form>

<script>
function check(theform) {
var myform = document.getemail;
var test = myform.myemail.value;
if (!testEmail(test)) {
window.alert(Please enter your email.);
return false; }
else { return true; }
}
function testEmail (chkMail) {
var emailPattern = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
var regex = new RegExp(emailPattern);
return regex.test(chkMail);
}
</script>
</body>
28
And LOTS
• You can play with:
more….
– Document appearance and content
• Dynamically create & modify HTML content
• Through DHTML/DOM
– Browser control
• Objects represent browser window
– HTML form interaction
• Objects represent browser contents
– User interaction
• Event handling
– Client state read/write
• Via cookies
– Applet interaction
29
Client-Side Validation
• HTML5
– Input types
• Email, url, number, password, date
– Input attributes
• Max, min, required, pattern
– Doesn’t work in all browsers
• JavaScript
– More complex checking
– More integrated error notifications
– But can be turned off

30
References

• http://www.w3schools.com/js/default.asp
Comments and Spacing
• Standard comment syntax
– Within a line
// comment here
– Block comment
/* start comment

end comment */
• Whitespace is ignored in JavaScript
– Spaces, tabs and blank lines do not affect the code
interpretation
Variables

• Variable names are case sensitive and


cannot contain punctuation, spaces, start with
a digit or be a JavaScript reserved word
• It is good practice to declare variables
var carName;
var pi = 3.14;
var person = "John Doe";
Variables and Types
• JavaScript is dynamically typed – variables can contain any type
and change types
– Number
– String
– Boolean
– Null
– Function
– Array
– Object
• The typeof operator can be used to find out the type of a variable
• A variable without a value has the type undefined
Operators
• Arithmetic
+ - / * % ++ --
• Assignment
= += -= *= /= %=
• Comparison
== === != !=== > < >= <=
• Logical
&& || !
• Conditional
voteable = (age < 18) ? "Too young":"Old enough";
JavaScript Functions
• JavaScript functions are declared using the
function keyword
function myFunction(a, b) { return a * b; }
• They can also be defined using an expression and
stored in a variable
var x = function (a, b) {return a * b};
var z = x(4, 3);
• The typeof operator will return “function” for
functions
Arrays
• Arrays can be created in two ways
– var cars = ["Saab", "Volvo", "BMW"];
– var cars = new Array("Saab", "Volvo", "BMW");
• Elements of an array can be accessed using an array index
number
– cars[0] = "Mini";
• You can have variables of different types within the same
array
• Arrays are a special type of object
Conditions and Loops
• JavaScript supports the following conditions
– if … else if … else and switch statements
• JavaScript supports the following kinds of loops
– for and for/in loops
<script>
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x] + " ";
}
</script>

– while and do … while

You might also like