Limited Time Offer: Get 2 Months of ABCmouse.com for only $5!

Web Dev II

Assignment N0. 1 (Short bondpaper, Written/Computerized)

1. What is a Script?

2. What is JavaScript?

3. Difference between Java & JavaScript.

4. What can JavaScript do into our Web?


LESSON 1                :               INTRODUCTION

What is a Script ?

A script is an executable list of commands like macro or batch file created by a scripting language. Scripts (like PHP, Perl) which are executed on a web server are called server-side scripts and scripts (like JavaScript) which are executed on user's computer, interpreted by the browser is called client-side scripts.

What is JavaScript ?

JavaScript is a cross-platform, object-oriented scripting language developed by Netscape. JavaScript was created by Netscape programmer Brendan Eich.

It was first released under the name of LiveScript as part of Netscape Navigator 2.0 in September 1995. It was renamed JavaScript on December 4, 1995. As JavaScript works on the client side, It is mostly used for client-side web development.

JavaScript is designed for use on web pages and closely integrated with HTML. JavaScript can create applications which run in the browsers such as IE, Opera, FireFox, Google Chrome and other. Netscape submitted JavaScript to ECMA International for standardization resulting in the standardized version named ECMAScript.

Are JavaScript and Java the same thing?

No, they are not.

Java (developed by Sun Microsystems) is a powerful and much more complex programming language in the same category as C and C++.

JavaScript was created by Brendan Eich at Netscape and was first introduced in December 1995 under the name of LiveScript. However, it was rather quickly renamed JavaScript, although JavaScript’s official name is ECMAScript, which is developed and maintained by theECMA (European Computer Manufacturer's Association) International organization.

JavaScript is a scripting language, that is, a lightweight programming language that is interpreted by the browser engine when the web page is loaded.

What can we do with JavaScript ?

Control the appearance of elements on your web page

Every web page is a collection of several individual elements which are called objects like an image, a link etc.

JavaScript is capable of controlling the appearance of many objects. For example you can open new pages in customized windows where you can specify their size, determine whether they have scroll bars or not etc.

JavaScript responds user actions on your web pages

JavaScript can control objects on web pages in response to various actions taken by the user which is called event. For example display a dialog box when an user clicks on a button, opening a new page, mouse over on a link to change the appearance of the link or control the background color of your web pages.

Display various date time format

JavaScript has the ability to retrieve the date and time of your computer's clock and it is enable to display various formatting of date-time through it's internal date object.

Perform calculations

JavaScript can perform wide variety of mathematical calculations. It has a library of all the mathematical constants and functions needed. These functions can be applied in different ways, for example an online financial transaction where JavaScript can be used to calculate subtotal, total etc, or an online calculator or creating games and interactive simulations with advance math functions such as sine and cosine.

Validate forms data

JavaScript can be used to validate form data including names, addresses, URL, email addresses, phone numbers, zip codes etc. in html forms before sending the data to a server. If you want to validate the said data in server side you have to wait while the information is sent up to the server for checking, using JavaScript you can detect the error and prompt the user immediately.


LESSON 2: YOUR FIRST JAVASCRIPT PROGRAM

The HTML

To insert a JavaScript script in an HTML page, you use the <script> ... </script> tag. Don't forget the closing </script> tag!

Let's start with a basic HTML page, like this one:

<html><head><title>My first JavaScript page</title></head>

<body>  </body>

</html>

 

The JavaScript script is inserted either in the HTML page itself or in a separate file.

 

Embed JavaScript in the HTML page

The <script> tag and its type attribute tell the browser: "Hey, browser! There's a script coming up, and it's a JavaScript script."

You can do this either in the <head> section, as follows:     

<html><head><title>My first JavaScript page</title>

<script type="text/javascript">

//JavaScript code goes here

</script>

</head>

<body></body>

</html>                  

 

Or at the very bottom of the document just before the closing </body> tag, like so:

<html><head><title>My first JavaScript page</title></head>

<body>

<script type="text/javascript">

//JavaScript code goes here

</script>

</body>

</html>                       

If you're wondering whether it's best to place your <script> tag in the <head> or the <body> tag, then you're not alone.

It mostly comes down to personal preference. However, because most of the times you'll want your JavaScript code to run after the web page and all its resources, e.g., stylesheets, graphics, videos, etc., have finished loading in the browser, I suggest you dump your JavaScript <script> tag at the bottom of your page.

 

Comments

One final thing to note about both code snippets above is the two forward slashes // before the text "JavaScript code goes here". This is how you comment a one-line JavaScript code.

When a comment spans over more than one line, you use /* Comment goes here */ to delimit a comment, just like you do in a stylesheet. Here's how it's done

<html><head><title>My first JavaScript page</title></head>

<body><script type="text/javascript">

/* JavaScript code

goes here */  

</script>

</body>

</html>

When the JavaScript interpreter in your browser comes across either '//' or '/* */', it just ignores whatever text is placed in between.

Use comments in your code to remind your future self of what your code is designed to do.

 

YOUR FIRST JAVASCRIPT (HELLO WORLD)

<html><head><title>My first JavaScript page</title></head>

<body><script type="text/javascript">

//JavaScript code goes here

alert('Hello World!');

</script>                                       

</body>

</html>

 

Let’s dissect the code given above:

Script - The script is an HTML element. Html script element is used to enclose client side scripts like JavaScript within an html document.

Type - This attribute specifies the scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). The attribute is supported by all modern browsers.

SRC - This attribute specifies the location of an external script. This attribute is useful for sharing functions among many different pages. Note that external JavaScript files contain only JavaScript statements and files must have the extension .js.

ALERT – this is a command to call an alert box use in JavaScript.

( ; ) - It tells the JavaScript interpreter that the statement is finished and whatever comes next is a different statement.

Make sure your <script>...</script> tags are there, that the text between the brackets is surrounded by quotes (' '), and that there is a semicolon ( ; ) at the end of the statement.


 LESSON 3:              JAVASCRIPT IN A SEPARATE FILE

Create a new document in your text editor and save it as "helloworld.js". Important: the file extension has to be .js (this is the appropriate JavaScript file extension).

In the new document, paste in the JavaScript command from the previous example (no need to type the <script> ... </script> tags here): 

                      alert('Hello World!');           

Now, go back to the HTML page, delete the previous JavaScript code, and add the <script> ... </script> tags in the <head> section of the page with a reference to the helloworld.js JavaScript file, like so:       

<html><head><title>My first JavaScript page</title>

<script type="text/javascript" src="helloworld.js"></script>

</head>

<body></body></html>

                                    

Save all your documents and run the HTML page in the browser. You should view the same alert box popping up as in the previous example.

If the code doesn't work, in your HTML document check that the filepath to the JavaScript file is correct, the filename spelling is accurate, and double-check that you've added a closing </script> tag.

In helloworld.js make sure your JavaScript command is typed exactly the same as in the sample code above, then try again.


Writing text string with document.write()

The easiest way to write or display something in a web page by using javascript, is document.write(). In this page and following some pages, we are going to see how we can use document.write() to write in webpages using JavaScript.

In the first example we are writing a string using document.write.

<html>

<head>
<title>JavaScript document.write example-1</title>
</head>
<body>
<script type="text/javascript">
document.write("Raquel Salazar")
</script>
</body>
</html>

Now, if we want to change the font properties of the string Raquel Salazar, we can add elements and attributes required for doing that:

<html>
<head>
<title>JavaScript document() example-2</title>
</head>
<body>
<script type="text/javascript">
document.write("<font color='blue' size='6pt'' weight='bold'>Raquel Salazar</font>")
</script>
</body>
</html>

 

If we want to display the string within a paragraph and want to align the string properly

<html>
<head>
<title>JavaScript document() example-3</title>
</head>
<body>
<script type="text/javascript">
document.write("<p align='center'>w3resource is a free online tutorial aiming beginners, intermediate and advanced users</p>")
</script>
</body>
</html>

Here is another example where a string is being displayed in two lines, using a html break element

 

<html>

<head>

<title>JavaScript document.write example-4</title></head>

<body>

<script type="text/javascript">

document.write("This is an example of text displayed in two lines <br>This tutorial approaches all the web development technologies you need to learn to start a career as a web developer")

</script>

</body>

</html>

 

Using document.write(), we can write strings with header element also.

<html>
<head>
<title>JavaScript document.write example-5</title>
</head>
<body>
<script type="text/javascript">

document.write("<h1>This example  has the following topics</h1><br><h2>html</h2><br><h3>css</h3><br><h4>javascript</h4><br><h5>xml</h5><br><h6>etc</h6>")
</script>

</body>
</html>

Writing string and variable with document.write()

<html >
<head>
<title>JavaScript document() example-6</title>
</head>
<body>
<script type="text/javascript">
var x
x=50
var y
y=25
document.write(x+"<br>"+y)
</script>
</body>
</html>

 

In the following web document we display a text string and variables, along with some html elements:

<html>
<head>
<title>JavaScript document() example-7</title>
</head>
<body>
<script type="text/javascript">
var x
x=10
var y
y=20
document.write("we are going to display two variables:"+ x +"&nbsp;"+ "and" + "&nbsp;" + y)
</script>
</body>
</html>

 

The following web document creates a list of variables, coupled with strings.

<html>

<head>

<title>JavaScript document.write example-8</title>

</head>

<body>

<script type="text/javascript">

var x

x=2000

var y

y=2004

var z

z=2008

var p

p=2012

document.write("We had these three leap years from year 2000:<br>" +

"<ul><li>" + x + "</li><br>" +

"<li>" + y + "</li><br>" +

"<li>" + z + "</li><br>" +

"<li>" + p + "</li><br>"

+ "</ul>" )

</script>

</body>

</html>

Writing html tables, string, variables with document.write()

In this page we are going to see how we can write html tables with document.write().

This is the first example: 

<html>
<head>
<title>JavaScript document() example-9</title>
</head>
<body>
<script type="text/javascript">
document.write("<table border='1' style='color:maroon; background-color: cornsilk;'><tr><td>" + "first row, first column" + "</td>" +
"<td>" + "first row, second column" + "</td>" +
"<td>" + "first row, third column" + "</td></tr>" +
"<tr><td>" + "second row, first column" + "</td>" +
"<td>" + "second row, second column" + "</td>" +
"<td>" + "second row, third column" + "</td></tr>" +
"<tr><td>" + "third row, first column" + "</td>" +
"<td>" + "third row, second column" + "</td>" +
"<td>" + "third row, third column" + "</td></tr></table>")
</script>
</body>
</html>

Here is another example where variables are displayed within a table with document.write()

<html><head>
<title>JavaScript document.write example-10</title></head>
<body><script type="text/javascript">
var x
x=1
var y
y=2
var z
z=3
document.write("<table border='1' style='color:blue; background-color: aliceblue;'><tr><td>"
+ x + "row" + x + "column" + "</td>" +
"<td>" + x + "row" + y + "column" + "</td>" +
"<td>" + x + "row" + z + "column" + "</td></tr>" +
"<tr><td>" + y + "row" + y + "column" + "</td>" +
"<td>" + y + "row" + y + "column" + "</td>" +
"<td>" + y + "row" + z + "column" + "</td></tr>" +
"<tr><td>" + z + "row" + x + "column" + "</td>" +
"<td>" + z + "row" + y + "column" + "</td>" +
"<td>" + z + "row" + z + "column" + "</td></tr></table>")
</script>
</body>
</html>


LESSON 4: JAVASCRIPT: Variables

VARIABLES – are generally used to temporarily store data. Its value can be changed at any point in the script or after a certain event is satisfied.

Rules when naming variables in JavaScript:

  1. Variable names are case sensitive
  2. They must begin with letter or underscore character
  3. You cannot use JavaScript reserved words as variable names.

JavaScript : Reserved Words

The words in the following table are reserved words and cannot be used as JavaScript variables, functions, methods, or object names. Some of these words are keywords, used in JavaScript ; others are reserved for future use.

List of reserved words

break

for

throw

case

function

try

catch

if

typeof

continue

in

var

default

instanceof

void

delete

new

while

do

return

with

else

switch

 

finally

this

 

 

How to declare variables

When declaring variables, we use the following syntax:

                var variable_name  (= initialization value)

It is possible to declare a variable even without var keyword as well as the initialization value.

                variable_name (= initialization value)

Variables can be declared anywhere in the part of the script before the part of the script that will be use.

Lifetime variables

Variables can only be accessed while the function or method running them is still active. Once the method is done processing, the variables and its value is being discarded.

JavaScript : Arithmetic Operators

Arithmetic Operators : +, -, *, /

In JavaScript, arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. There are four standard arithmetic operators, addition (+), subtraction (-), multiplication (*), and division (/).

In addition, JavaScript provides modulus(%), increment(++), decrement(--) and unary negation(-) operators. 

Example : ( + addition operator)

<html><head><title>JavaScript + operator example</title></head>

<body><h1 style="color: red">JavaScript + operator example</h1><hr/>

<script type="text/javascript">

//This is a sample of Addition in JavaScript

var1 = 45;

var2 = 78;

var3 = 45.10;

var4 = 178.12;

newvar+ = var1 + var2;

newvar1 = var3 + var4;

document.write("var1 + var2 = ", newvar + "<br>");

document.write("var3 + var4 = ", newvar1);

</script></body></html>

 

Example : ( - subtraction operator)

<html><head><title>JavaScript - operator example</title></head>
<body><h1 style="color: blue">JavaScript - operator example</h1><hr />
<script type="text/javascript">
var1 = 45;
var2 = 78;
str1 = "raquelsalazar.educatorpages";
str2 = ".com";
newvar = var1 - var2;
newstr = str1 - str2;
varstr = var1 - str2;
document.write("var1 - var2 = ", newvar, "<br>");
document.write("str1 - str2 = ", newstr, "<br>");
document.write("var1 - str2 = ", varstr);
</script>
</body>
</html>

 

Example : ( - multiplication operator)

<html><head><title>JavaScript * operator example</title>
</head><body>
<h1 style="color: red">JavaScript * operator example</h1><hr />
<script type="text/javascript">
var1 = 45;
var2 = 78;
var3 = 45.10;
var4 = 178.12;
newvar = var1 * var2;
newvar1 = var3 * var4;
document.write("var1 * var2 = ", newvar, "<br>");
document.write("var3 * var4 = ", newvar1, "<br>");
</script></body></html>
 

Example : ( / division operator)

<html><head><title>JavaScript / operator example</title></head>
<body>
<h1 style="color: red">JavaScript / operator example</h1><hr />
<script type="text/javascript">
var1 = 45;
var2 = 78;
var3 = 1;
var4 = 2;
newvar = var1 / var2;
newvar1 = var3 / var4;
document.write("var1 / var2 = ", newvar+"<br />");
document.write("var3 / var4 = ", newvar1);
</script>
</body>
</html>

 

Arithmetic Special Operators

In addition to four standard arithmetic operators (+, -, *, /), JavaScript provides the following arithmetic operators.

JavaScript Modulus operator (%)  The modulus operator is used as follows: var1 % var2

The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the above statement, where var1 and var2 are variables.

The modulo function is the integer remainder of dividing var1 by var2. The result will have the same sign as var1.

Example : modulus operator ( %)

<html >
<head>
<title>JavaScript operator(%) example</title>
</head>
<body>
<h1 style="color: red">JavaScript modules operator(%) example</h1>
<hr />
<script type="text/javascript">
var1 = 45;
var2 = 78;
var3 = -45.10;
var4 = 178.12;
newvar = var1 % var2;
newvar1 = var3 % var4;
document.write("var1 % var2 = ", newvar, "<br>");
document.write("var3 % var4 = ", newvar1, "<br>");
</script>
</body>
</html>

JavaScript alert - Dialog box

Description

alert() is a simple function to display a message to a dialog box (also called alert box). Here is a simple example to display a text in the alert box.

<html>
<head>
<title>Javascript alert box example-1</title>
</head>
<body>
<h1 style="color: red">JavaScript alert() box example</h1>
<hr />
<script type="text/javascript">
alert("This is a alert box");
</script>
</body>
</html>

Let's puts some variables in the alert box.

<html><head><title>JavaScript alert box example-2</title></head>

<body>

<h1 style="color: red">JavaScript alert() box example</h1><hr />

<script type="text/javascript">

mess1="Highest marks in Mathematics : ";

math=99;

alert(mess1+math);

</script>

</body>

</html>

JavaScript confirm - Dialog box

Description

Confirm() displays a dialog box with two buttons, OK and Cancel and a text as a parameter. If the user clicks on OK button, confirm() returns true and on clicking Cancel button, confirm() returns false.

See the following web document.

<html><head><title>JavaScript confirm box example </title></head>
<body>
<h1 style="color: red">JavaScript confirm() box example</h1><hr />
<script type="text/javascript">
mess1='Press Ok to Continue.';
math=99;
x = confirm(mess1);
if (x == true)
{
alert("You have clicked on Ok Button.");
}
else
{
alert("You have clicked on Cancel Button."); }
</script>
</body>
</html>

JavaScript prompt - Dialog box

Description

The alert() method can not interact with the visitor. To interact with the user we use prompt(), which asks the visitor to input some information and stores the information in a variable.

<html><head><title>JavaScript prompt() example-2</title></head>

<body>

<script type="text/javascript">

visiter_name = prompt("Input your name : ")

if(visiter_name != null && visiter_name != "")

alert("Your Name is : "+visiter_name);

else

alert("Blank name ...!")

</script></body></html>

 

Another Example

<html><head>

<title> Using Prompt() box </title></head>

<body>

<script type="text/javascript">

name = prompt ("Please Enter your Name", "Type Here")

</script></body></html>

 


July 24, 2012

ASSIGNMENT:

1. Create a log-in page, a link that will prompt the user to an account creation.

2. At the account creation page, create a form for the username, password and a secret question. Create a promptbox that will enable the user to create a secret question.

3. After filling in the necessary information, the user may click the create account button. Furthermore, clicking so will produce an alert box that you have successfully created an account.


LESSON 5:  CONDITIONAL STATEMENTS

-are used to perform different operations based on the set conditions.

There are different kinds of conditional statements. These are:

IF STATEMENT – used to check if a specified condition is true.

IF-ELSE STATEMENT – used to check if the condition is true and performs an action if the condition is false.

SWITCH STATEMENT – used if you want to select one of many blocks of code to be executed.

 

 

IF STATEMENT

The If statement is extensively used for this purpose, to take decision on the basis of the information you provide.

It's actually quite simple to use the if statement and here is the format of an if statement.

if (condition)

{

   statements to execute

}

When JavaScript encounters an if statement, it checks the condition. If and only if, it is found to be true, the statements enclosed within the curly braces are executed. Note, the condition is always enclosed by a pair of parenthesis.

Let's look at some examples.

<html><head><title>if statement</title></head>

<body>

<script type="text/javascript">

var a = 5;

var b = 5;

if (a == b)

   {

   alert("The two quantities are equal");

   }

</script>

</body>

</html>

First, two variables are initialized and assigned the same numeric value (5). The if statement then checks for their equality and pops-up an alert box if the two variables are equal.
The == comparison operator does the job of checking the two variables. The other Comparison operators are:

  • !=   Not equal to
  • <   Less than
  • >   Greater than
  • <=   Less than or equal to
  • >=   Greater than or equal to

The == is a 'Comparison Operator' while = is an 'Assignment Operator'. Be sure to use the comparison operator in a condition. If you use the assignment operator, the code will not function and JavaScript will NOT throw an error... it'll simply reassign the variable on the left.

Another example

<html>

<head>

<title>if statement</title></head>

<body>

<script type="text/javascript">

var get_res = confirm("Did you like this session?");

if (get_res == true)

{

alert("Okay! Let's proceed to the next");

}

</script>

</body>

</html>

 

IF-ELSE STATEMENT

Each condition has two paths from which we choose one. For example, "If it's raining, I'll stay at home else I'll go out for a stroll."

Just like the conditions of everyday life, the conditional if statement in JavaScript has an else clause. It allows us to take the alternate path when the condition in if is false.

Example:

<html>

<head>

<title>if statement</title></head>

<body>

<script type="text/javascript">

var weather = "raining";

if (weather == "raining")

   {

   alert("I'll stay at home");

   }

else

   {

   alert("I'll go out for a stroll");

   }

</script>

</body>

</html>

 

We can extend our if statement we met in the previous session to construct a better confirm box.

 

<html>

<head>

<title>if statement</title></head>

<body>

<script type="text/javascript">

var response = confirm("Have you understood the confirm box?");

if (response == true)

   {

   alert("Okay, let us continue");

   }

else

   {

   alert("Go thru the previous session again");

   }

</script>

</body>

</html>

    

SWITCH STATEMENT

JavaScript Switch Statement function is like the if statement. It is a conditional statement; however, only one variable is taken into consideration and bears the condition. You can also use it to select one or more blocks of code to be executed. To prevent it from executing other blocks of code after it continuously, you must use the break statement.

Example:

<html>

<head><title>Switch Statement</title></head>

<body>

<script type= text/javascript>

//this program will printout the equivalent value of a roman numeral

var input = "I";

switch (input)

{

case "I":

                               document.write("This is equivalent to One");

                              break;

case "V":

                               document.write("This is equivalent to Five");

                               break;

case "X":

                               document.write("This is equivalent to Ten");

                               break;

default:

                               document.write("Not yet available");

}

</script>

</body>

</html>

 

Example using Function

<html>

<head>

<title>JavaScript switch statement : Example-1</title>

</head>

<body>

<h1 style="color: red">JavaScript : switch statement</h1>

<h3> Input a grade [ A+, A, B+, B, C ] in the textbox and you will get the idea of the marks. 'A' appeared as a default value.</h3>

<hr />

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

function marksgrade()

{

grade = document.form1.text1.value;

switch (grade)

{

case 'A+':

alert("Marks >= 90");

break;

case 'A':

alert("Marks [ >= 80 and <90 ]");

break;

case 'B+':

alert("Marks [ >= 70 and <80 ]");

break;

case 'B':

alert("Marks [ >= 60 and <70 ]");

break;

case 'C':

alert("Marks < 60");

break;

default:

alert("Wrong grade.........");

}

}

//]]>

</script>

<form name="form1" action ="#">

Input Grade type : <input type="text" name="text1" value="A" />

<br /><br />

<input type="button" value="Marks check"

onclick='marksgrade()' />

</form>

</body>

</html>

 

Get 2 Months for $5!