Indulekha nadikuppam csi 668
This presentation is the property of its rightful owner.
Sponsored Links
1 / 83

Indulekha Nadikuppam csi 668 PowerPoint PPT Presentation


  • 73 Views
  • Uploaded on
  • Presentation posted in: General

JavaScript. Indulekha Nadikuppam csi 668. What is JavaScript?. JavaScript is a programming language that is used to add interactivity to Web Pages. Netscape invented JavaScript as a way to control the browser and add flash and interactivity to Web pages.

Download Presentation

Indulekha Nadikuppam csi 668

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Indulekha nadikuppam csi 668

JavaScript

Indulekha Nadikuppam

csi 668


What is javascript

What is JavaScript?

  • JavaScript is a programming language that is used to add interactivity to Web Pages.

  • Netscape invented JavaScript as a way to control the browser and add flash and interactivity to Web pages.

  • JavaScript is often referred to as “scripting language”.

  • A scripting language is a light weight programming language, which is easy and fast to learn.


What is javascript1

What is JavaScript?

  • JavaScript is an interpreted language means it is not compiled. It is interpreted during run-time.

  • JavaScript is a client side language and it runs on client web browser.

  • JavaScript can be also used on the server-side.


What is javascript2

What is JavaScript?

  • A JavaScript is a program that is embedded directly into HTML pages

  • Because it is enclosed in the <SCRIPT> tag, the text of the script doesn’t appear on the user’s screen, and the web browser knows to run the JavaScript program.

  • You can validate text fields, disable buttons, validate forms, or change the background color of your page.


What javascript can do

What JavaScript Can Do?

  • JavaScript creates an active user interface, giving the users feedback as they navigate web pages.

  • For example, websites have buttons that highlight as mouse pointer moves over them. That’s done using JavaScript, using a technique called rollover.

  • JavaScript is used in Web pages to ensure that the user entered valid information in forms which can save business times and money.

  • If a web form requires calculations, JavaScript can do them on the user’s machine without needing to use a complex server CGI.


Javascript is object based

JavaScript is Object-Based

  • JavaScript is not a full-blown Object-Oriented language

  • An object-based language is an object-oriented language with a collection of objects built right into the language

  • For example, we don’t have to build a “date” object in JavaScript because there is already one to use


Object oriented nature of html

Object-Oriented Nature of HTML

  • JavaScript considers HTML an object-oriented language, where the various HTML tags correspond to different types of JavaScript objects

    <html>

    <head>

    <title>This is a title</title>

    </head>

    <body>

    <a href = “http://www.myhome.com”> My Home</a>

    <form>

    <input type = “button” name = *Button1*>

    </form>

    </body>

    <html>


Object oriented nature of html1

Object-Oriented Nature of HTML

  • JavaScript objects for the html page are:

  • Document. title = “This is a title”(from the <title> tag)

  • Document. form (the form on the page)

  • Document.form.Button1(the button on the form)

  • Every HTML element can be used as an object


What javascript can do1

What JavaScript Can Do?

  • JavaScript controls the browser, so you can open up new windows, display alert boxes, and put custom messages in the status bar of the browser window

  • JavaScript has a set of date and time features, to generate clocks, calendars, and timestamp documents

  • Thus JavaScript provides site’s users with a better, more exciting experience


Javascript is event driven

JavaScript Is Event-Driven

  • Whenever something happens on a Web page, an event occurs.

  • Events can be just about anything- a button is clicked, the mouse is dragged, a page is loaded, a form is submitted, and so on.

  • JavaScript is event-driven in that it’s designed to react when an event occurs. How it reacts depends upon the program

  • JavaScript has 9 event handlers to interface script with system activities and user responses and actions

  • These 9 event handlers can be classified into 2 categories

    System events

    Mouse events


System events

System Events

  • System events don’t require user interaction in order to be activated

  • For example, you can signal that a page has finished loading, that a page is about to be unloaded, or that a period of time has elapsed.

    Onload and onUnload:

  • The onload and onUnload events are triggered when the user enters or leaves the page.

  • The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

  • Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".


Mouse events

Mouse Events

  • Mouse events require user interaction in order to be triggered

    Onclick: The most of the mouse events is the Onclick handler. This event is activated whenever you click an object that accepts such an event. Objects accepting onclick events are links, check boxes, and buttons

    OnFocus: Focus occurs when an object becomes the item in focus. This happens when the user clicks or tabs to the particular object, that object has the focus

    onMouseOver and onMouseOut: onMouseOver and onMouseOut are often used to create "animated" buttons.

    Ex:- <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"> <img src="w3schools.gif" width="100" height="30"> </a>


Javascript is secure

JavaScript Is Secure

  • JavaScript is designed to manipulate and present information through the browser, but it can’t retrieve information from another file or to save data to the Web server or the user’s computer.

  • It’s not possible to write a JavaScript program that would scan a computer’s directories and retrieve a user’s files


Javascript is platform independent

JavaScript is Platform-Independent

  • JavaScript isn’t bound to a particular computer.

  • It is just bound to the browser that interprets it

  • JavaScript can run on Macintosh, Windows, or Unix copy of Netscape navigator


Are java and javascript the same

Are Java and JavaScript the same?

  • Despite the name, JavaScript and Java have almost nothing to do with one another

  • Java and JavaScript are two completely different languages in both concept and design

  • Java is a full-featured object-oriented programming language, much more complex than JavaScript


Javascript isn t java

JavaScript isn’t Java

  • Java is compiled to byte codes on the server and the result is send to the client. JavaScript is interpreted on the client side. It doesn’t require any compilation.

  • JavaScript is embedded within an HTML document as plain text. Java applets are referenced from a document, but the code is kept in a separate file in binary form

  • JavaScript uses dynamic binding, which means that object references are checked at runtime. Java, on the other hand, uses static binding, in which object references must exist when the program is compiled


Javascript isn t java1

JavaScript isn’t Java

  • JavaScript is identified within a document by the <SCRIPT> tag. Java applets are embedded in a document using the <APPLET> tag

  • JavaScript uses loose typing, meaning the variables don’t have to be declared, and the variable that was used as a string could be used as a number later. Java uses strong typing, which means the variables must be declared and used as a particular type


Javascript guidelines

JavaScript Guidelines

Case-Sensitive

  • JavaScript is a case-sensitive language

    Ex: - “X” and “x” are both different variables.

  • The same is valid for functions

    Ex: - If you define a function with the name “GetValues” and call it with the name “Getvalues”, then you wont see any processing. Both are different functions.


Javascript guidelines1

JavaScript Guidelines

Symbols

  • All opened symbols must be closed properly. If you started a string with " then you should also close it with ". Otherwise, the page wont executed correctly.

    Ex: - {} This is mostly used in functions or in condition statements.

    function x()

    {

    }


Javascript guidelines2

JavaScript Guidelines

Ex: - [] This is used in arrays.

var arTest = new Array(2)

arTest[0] = "string1"

arTest[1] = "string2”

arTest[2] = "string3”

Ex:- "“ This is usually used in strings.

var mystr = "this is a string."

Ex:- '‘ This can be also used in strings.

var mystr = 'this is a string'


Javascript guidelines3

JavaScript Guidelines

NoScript

  • Some users don’t allow or don’t want to run a JavaScript on the browser.

  • In that case you should always use the <noscript> tag to displays a message that JavaScript is either disabled or not supported by the browser


Javascript special characters

JavaScript Special Characters

  • The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.

    Suppose

    var txt="We are the so-called "Vikings" from the north."

    document.write(txt)

  • In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called


Javascript special characters1

JavaScript Special Characters

  • To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:

    var txt="We are the so-called \"Vikings\" from the north.";

    document.write(txt);

  • JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.

    Ex:- document.write ("You \& I are singing!"); 

    You & I are singing!


Javascript guidelines4

JavaScript Guidelines

Values and Variables

In JavaScript, a piece of information is a value

Variables contain values. Way to assign value “John” to variable myName is myName = “John”.

Variable names cannot contain spaces or other punctuation

Value Types

Type

Number

String

Boolean

Null

Object

Function

Description

Any numeric value

Characters inside quote marks

True or False

Empty and meaningless

Any value associated with the object

Value returned by a function


Javascript guidelines5

JavaScript Guidelines

  • As in any programming language, there is way to put comments in JavaScript also

  • Comments can be either created in one line with // or in multiple lines with /*…*/.

    Ex:-

    // Please comment only this line

    /* Everything between these

        signs, will be commented out.

    */


Where to put scripts

Where to Put Scripts

  • Scripts can be used in either of two places on an HTML page: between the <HEAD> and </HEAD> tags, or between the <BODY> and </BODY> tags

  • To insert a JavaScript into an HTML page, we use the <script> tag.

  • Inside the <script> tag we use the "type=" attribute to define the scripting language.

  • So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends.


Example

Example

<html>

<head>

<title> My first script </title>

</head>

<body>

<script type="text/javascript">

document. write(“Hello, world”);

</script>

</body>

</html>


Scope

Scope

  • Variables can be either defined globally or locally.

  • If you define a variable in a function then it is a local variable.

  • The variable is not accessible out of the function.

  • As soon as the function ends the variable is destroyed.

  • If you define a variable outside of a function, then it is called a global variable.

  • This variable is available and accessible everywhere.


Example1

Example

<html>

<head>

<script type="text/javascript">

            var globalVar = "This is a global variable.<br/>"

            function X()

            {

                        var globalVar = "Is the value changed ?<br/>"

                        document.write(globalVar)

            }

            X()

            document.write(globalVar)

</script>

</head>

<body></body>

</html>

Output:

Is the value changed ?

This is a global variable.


Alerting the user

Alerting the User

  • One of the main uses of JavaScript is to provide feedback to people browsing the site

  • Alert window can be used to pop up vitally important information

    To alert a user:

    alert(“Welcome to my JavaScript page!”)


Example2

Example

<html>

<body>

<script type="text/javascript">

alert ("Welcome to my JavaScript page!")

</script>

</body>

</html>


Confirm box

Confirm Box

  • A confirm box is often used if you want the user to verify or accept something.

  • When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

  • If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

    Syntax: confirm("some text");


Prompt box

Prompt Box

  • A prompt box is often used if you want the user to input a value before entering a page.

  • When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

  • If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

  • Syntax: prompt("some text", "default value");


Using an external javascript

Using an External JavaScript

  • Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page.

  • To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension.

  • The external script cannot contain the <script> tag!

  • To use the external script, point to the .js file in the "src" attribute of the <script> tag:


Example3

Example

<html>

<head>

<script src="xxx.js">

</script>

</head>

<body>

</body>

</html>


Javascript arrays

JavaScript Arrays

  • Arrays are variables, which can contain multiple values.

  • Arrays are created always with the new keyword

    Assigning Values

  • The values can be assigned in two ways. Either without defining the size and index or by defining the size and index number.

    Example:- var days= new Array(“Sunday”, “Monday”, “Tuesday”, “Thursday”, “Friday”, “Saturday”);

    Or

    var days = new Array(7)

    var days[0] = “ Sunday”


Javascript array object functions

JavaScript Array Object Functions

The Array object contains 10 functions.

  • JavaScript join Function:- The join function can be used to join the content of an array to a single string, separated with a character of your choice. If you don’t specify one, it will use the comma by default.

    Example:- <html>

    <head>

    <script type="text/javascript">

                var arJoin = new Array("11", "12", "13", "14", “15”)

                document.write(arJoin.join("|"))

    </script>

    </head>

    <body></body>

    </html>

    Output

    11|12|13|14|15


Javascript array object functions1

JavaScript Array Object Functions

2. JavaScript concat Function:- The concat function can be used to join two arrays together to one array

Example:-

<html>

<head>

<script type="text/javascript">

            var ar1 = new Array("11", "12", "13", "14", “15”)

            var ar2 = new Array("16", "17", "18", "19", “20”)

            document.write(ar1.concat(ar2))

</script>

</head>

<body></body>

</html>

Output

11,12,13,14,15,16,17,18,19,20


Javascript array object functions2

JavaScript Array Object Functions

3. JavaScript pop Function:- The pop function can be used to retrieve the last element of an array

Example:-

<html>

<head>

<script type="text/javascript">

            var ar1 = new Array("11", "12", "13", "14", “15”)

            document.write(ar1.pop())

</script>

</head>

<body></body>

</html>

Output

15


Javascript array object functions3

JavaScript Array Object Functions

4. JavaScript push Function:- The push function can be used to add one ore more new elements to an array

Example:-

<html>

<head>

<script type="text/javascript">

            var ar1 = new Array("11", "12", "13", "14", “15”)

           ar1.push("16","17")

           for(var i = 0;i<ar1.length;i++)

                        document.write(ar1[i]+" | ")

</script>

</head>

<body></body>

</html>

Output

11 | 12 | 13 | 14 | 15 | 16 | 17 |


Javascript array object functions4

JavaScript Array Object Functions

5. JavaScript reverse Function:- The reverse function can be used to reverse the order of the elements in an array. The first will become the last and the last will become the first.

<html>

<head>

<script type="text/javascript">

            var arRev = new Array("11", "12", "13", "14", “15”)

            document.write("Before Reverse: " + arRev + "<br/>")

            document.write("After Reverse: "+arRev.reverse())

</script>

</head>

<body></body>

</html>

Output

Before Reverse: 11,12,13,14,15

After Reverse: 15,14,13,12,11


Javascript array object functions5

JavaScript Array Object Functions

6. JavaScript shift Function:- The shift function can be used to remove the first element of an array. It also returns the first element.

Example:-

<html>

<head>

<script type="text/javascript">

           var arShift = new Array("11", "12", "13", "14", “15”)

            document.write(arShift.shift())

</script>

</head>

<body></body>

</html>

Output

11


Javascript array object functions6

JavaScript Array Object Functions

7. JavaScript slice Function:-

  • The slice method can be used to create a new array from a specific range in an array.

  • You have to define the starting position. You can also define the end position, however if you do not specify it then it will get the array position from your starting point to the end point of the array.


Javascript array object functions7

JavaScript Array Object Functions

Example:-

<html>

<head>

<script type="text/javascript">

            var arSlice = new Array("11", "12", "13", "14", “15”)

           document.write(arSlice.slice(2,4) + "<br>")

            // Without defining end

            document.write(arSlice.slice(2))

</script>

</head>

<body></body>

</html>

Output

13,14

13,14,15


Javascript array object functions8

JavaScript Array Object Functions

8. JavaScript splice Function:- The splice function can be used to add or remove elements of an array. You need to specify the starting position and how many elements to remove.

<html>

<head>

<script type="text/javascript">

            var arSplice = new Array("11", "12", "13", "14", “15”)

            document.write(arSplice.splice(2,3, "99") + "<br>")

            // adding new elements

            document.write(arSplice)

</script>

</head>

<body></body>

</html>

Output

13,14

11,12,15,99


Javascript array object functions9

JavaScript Array Object Functions

9. JavaScript sort Function:-

  • The sort function can be used to sort the elements in an array.

  • You can also create a separate compare function to use with sort.

  • However if you do not, then it will convert all elements to strings and sort them in dictionary order. This can cause problems when you have integers in an array and need to sort them – i.e.: 11 would come before 3.


Javascript array object functions10

JavaScript Array Object Functions

<head>

<script type="text/javascript">

            var arSort = new Array("11", "10", "7", "8", "9")

            document.write("Normal sorting: " + arSort.sort() + "<br>")

            function SortNumeric(x,y)

            {

                        return x-y

              }

            document.write("Sorting with function: " + arSort.sort(SortNumeric))

</script>

</head>

<body></body>

</html>

Output

Normal sorting: 10,11,7,8,9

Sorting with function: 7,8,9,10,11


Javascript array object functions11

JavaScript Array Object Functions

10. JavaScript unshift Function:- The unshift function can be used to add new elements at the beginning of the array. This function only works on Netscape.

<html>

<head>

<script type="text/javascript">

            var arUnshift = new Array("11", "12", "13", "14", "15")

           document.write(arUnshift.unshift("8","9","10"))

</script>

</head>

<body></body>

</html>

Output

8,9,10,11,12,13,14,15


Javascript boolean object

JavaScript Boolean Object

  • The Boolean object is a wrapper for the Boolean data type.

  • The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

  • Boolean object is defined with the new keyword

    var myBoolean=new Boolean();

  • If the Boolean object has no initial value or if it is 0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string "false")!


Javascript boolean object1

JavaScript Boolean Object

  • All the following lines of code create Boolean objects with an initial value of false

    var myBoolean=new Boolean();

    var myBoolean=new Boolean(0);

    var myBoolean=new Boolean(null);

    var myBoolean=new Boolean("");

    var myBoolean=new Boolean(false);

    var myBoolean=new Boolean(NaN);


Javascript boolean object2

JavaScript Boolean Object

  • The following lines of code create Boolean objects with an initial value of true

    var myBoolean=new Boolean(true);

    var myBoolean=new Boolean("true");

    var myBoolean=new Boolean("false");

    var myBoolean=new Boolean("Richard");


Javascript conditional statements

JavaScript Conditional Statements

  • Conditional statements can be used to perform certain tasks depended on the condition.

  • There are two different condition statements: if…else and switch.

  • The following example checks if the variable x is empty. If it is empty then it will show an error message.


Example of if statement

Example of if statement

<html>

<head>

<script type="text/javascript">

            var x = ""

            if( x == ""){

                        document.write("Error: Variable is empty<br/>")

                        document.write("Please fill the variable.")

            }

            else

                        document.write(x)

</script>

</head>

<body></body>

</html>

Output:

Error: Variable is empty

Please fill the variable.


Switch statement

Switch statement

Switch statements works the same as if statements. However the difference is that they can check for multiple values.

<html>

<head>

<script type="text/javascript">

            var light = "green"

            switch(light)

            {

                        case "red":

                                    document.write("You can not drive now.")

                                    break

                        case "yellow":

                                    document.write("You can drive if you want.")

                                    break

                        case "green":

                                    document.write("You can drive now.")

                                    break

                        default:

                                    document.write("Light is not working...")

            }

</script>

</head>

<body></body>

</html>

Output: You can drive now


Javascript loops

JavaScript Loops

  • Loops can be used to repeat something again and again till a condition returns false or true depending on how you need it.

  • There are three types of loops: do…while, while and for loop. The following examples show each loop:

    Example of do … while loop

    <html>

    <head>

    <script type="text/javascript">

                var i = 0

                do

                {

                            i++

                            document.write(i+"<br>“)

                }while(i<3)

    </script>

    </head>

    <body></body>

    </html>

    Output

    1

    2

    3


Javascript loops1

JavaScript Loops

Example of while loop

<html>

<head>

<script type="text/javascript">

            var i = 0

            while(i<3)

            {

                        i++

                        document.write(i+"<br>")

            }

</script>

</head>

<body></body>

</html>

Output

1

2

3


Javascript loops2

JavaScript Loops

For loop:- A for loop is executed till a condition returns false. It has basically the same syntax as in other languages.

Example

<html>

<head>

<script type="text/javascript">

            for(var i=0;i<3;i++)

            {

                        document.write(i+"<br>")

            }

</script>

</head>

<body></body>

</html>

Output

0

1

2


Javascript functions

JavaScript Functions

  • Functions are an important part in any programming language.

  • JavaScript contains some inbuilt functions, which can be used freely and you can create your own functions. 

  • A function contains of name and a body.

  • Each function starts with the keyword function and then the name of the function. After that you can put your required commands in the body part which must be enclosed with the {} brackets. Once you have created your function you can call it with the name of the function.


Javascript function

JavaScript Function

<html>

<head>

<script type="text/javascript">

            // Create a function

            function X(number)

            {

            document.write("This is a function with parameters.<br/>")

            var PI = 3.14

            document.write(number*PI+"<br/>")

            }

            // Call the function

            X(4)

</script>

</head>

<body></body>

</html>

Output:

This is a function with parameters.

12.56


Javascript date object

JavaScript Date Object

  • The JavaScript Date Object can be used to work with dates and times.

  • It contains 17 functions to set or retrieve date time values.

  • Since JavaScript is a client side language and the script runs on the client, therefore it will always return the date/time of the client, not the date/time of the server.

  • When you create a clock make sure that you use a span tag or something similar, but do not use document.write to displays the time - document.write does not work really good with that object.

  • Here is a clock in a very simple way, which refresh automatically each second to update the time.


Javascript date object1

JavaScript Date Object

Example

<html>

<head>

<script type="text/JavaScript">

            function Clock()

            {

                        var d = new Date()

                        clock.innerHTML = d

                        setTimeout("Clock()",1000)

            }

            window.onload=Clock

</script>

</head>

<body>

            <span id=clock></span>

</body>

</html>

Output

Sun Feb 10 11:49:52 CST 2008


Javascript date object functions

JavaScript Date Object Functions

  • getDate:- This function can be used to return the current date. It returns a value between 0 and 31 depending on the month.

  • getHours:- The getHours function can be used to return the current hour. It will return a value between 0 and 23.

  • getMinutes:- This function can be used to return the current minutes. The return value is between 0 and 59.

  • getMonth:-The getMonth can be used to return the current month. The return value is between 0 and 11.


Javascript date object functions1

JavaScript Date Object Functions

  • getSeconds:- This function can be used to return the current seconds. The return value is between 0 and 59. If you press the F5 button after few seconds, you will see that how the seconds increase.

  • getTimezoneOffset:- This function can be used to return the minutes between your time and GMT.

  • getYear :-The getYear function can be used to return the current year. It will return the year in the format YYYY.

  • setDate :- This function can be used to set the date of the month. The value must be between 1 and 31 depending on the current month.


Javascript date object functions2

JavaScript Date Object Functions

  • setHours:- This function can be used to set the hours. The value must be between 0 and 23.

  • setMinutes:- The setMinutes function can be used to set the minute. The value must be between 0 and 59.

  • setMonth:- The setMonth function can be used to set the current month. The value must be between 0 and 11, where 0 is January and 11 is December.

  • setSeconds Function:- The setSeconds can be used to set the current seconds. The value must be between 0 and 59.


Javascript date object functions3

JavaScript Date Object Functions

  • setTime :- The setTime function can be used to set the date and time. The value is an integer which represents the number of seconds since midnight January 1, 1970 GMT.

  • setYear:- The setYear function is used to set the current year.

  • toGMTString:- This function can be used to convert the date to a string using the GMT convention.

  • toLocaleString Function:-This function can be used to convert a date to the local machine settings


Javascript date object functions4

JavaScript Date Object Functions

  • UTC:- The UTC function can be used to convert the number of milliseconds between January 1, 1970 and the date, which you pass to the UTC function. This function has to be called with the following syntax: Date.UTC(Year, Month, Date, Hour, Minute, Sec)


Javascript form

JavaScript Form

  • Forms are basically used to allow the user to enter some information, which will then used for further processing on the server.

  • However before the processing takes place, JavaScript is used to validate the form – i.e. does the user entered all required information?

  • JavaScript provides many functions, which makes it easy to work with forms.


Javascript form validation

JavaScript Form Validation

  • JavaScript can be used to validate input data in HTML forms before sending off the content to a server.

  • Form data that typically are checked by a JavaScript could be:

  • has the user left required fields empty?

  • has the user entered a valid e-mail address?

  • has the user entered a valid date?

  • has the user entered text in a numeric field?


Javascript form1

JavaScript Form

  • In the following example, I have created a form and a function “GetFormValues()”.

  • This function retrieves all values from the form and validates them.

  • Only the name fields are validated, the radio buttons can be selected or not.

  • If the user doesn’t enter the first name or the last name in the fields, then it will show an error message next to the textbox.

  • Once the user has entered the information the form is validated and the user information is shown in the browser.


Example4

Example

  • <html>

  • <head>

  • <script type="text/javascript">

  • function GetFormValues()

  • {

  • // Get the form

  • var myForm = document.myform

  • // Get the value from the element firstName

  • var firstName = myForm.firstName.value

  • var lastName = myForm.lastName.value

  • var bMale = myForm.gender[0].value

  • var bFemale = myForm.gender[1].value


Example5

Example

  • firstName = firstName

  • if(firstName == "")

  • spfirstName.innerHTML = "Please enter the first name"

  • else

  • spfirstName.innerHTML = ""

  • if(lastName == "")

  • splastName.innerHTML = "Please enter the last name"

  • else

  • splastName.innerHTML = ""

  • if(firstName != "" && lastName != ""){

  • document.write("Thanks <b>" + firstName + " " + lastName + "</b> for entering the information.<br/>")

  • if(!bMale || !bFemale)

  • document.write("However you havent selected your gender!")

  • else{

  • var gender = (bMale == true) ? "Male" : "Female"

  • document.write("Your gender is: " + gender)

  • }


Example6

Example

  • }

  • }

  • </script>

  • </head>

  • <body>

  • <form name="myform">

  • * First Name: <input type="text" name="firstName"/>

  • <span ID="spfirstName" style="color:red"></span><br/>

  • * Last Name: <input type="text" name="lastName"/>

  • <span ID="splastName" style="color:red"></span><br/><br/>

  • Male: <input type="radio" name="gender" value="male">

  • Female: <input type="radio" name="gender" value="female">

  • <input type="button" value="Click Me!" onclick="GetFormValues()">

  • </form>

  • </body>

  • </html>


Javascript string object

JavaScript String Object

  • The String object is used to manipulate a stored piece of text.

  • Examples of use:

  • var txt="Hello world!";

  • document.write(txt.length);

  • document.write(txt.toUpperCase());


Javascript regexp object

JavaScript RegExp Object

  • RegExp, is short for regular expression.

  • When you search in a text, you can use a pattern to describe what you are searching for.

  • RegExp IS this pattern.

  • A simple pattern can be a single character.

    Defining RegExp

  • The RegExp object is used to store the search pattern.

  • We define a RegExp object with the new keyword. The following code line defines a RegExp object called pat with the pattern "e":

  • var pat=new RegExp("e");


Methods of the regexp object

Methods of the RegExp Object

  • The RegExp Object has 3 methods: test(), exec(), and compile().

    test()

  • The test() method searches a string for a specified value. Returns true or false

  • Example:

  • var pat=new RegExp("e");

  • document.write(pat.test("The best things in life are free"));

  • Since there is an "e" in the string, the output of the code above will be: true


Methods of the regexp object1

Methods of the RegExp Object

exec()

  • The exec() method searches a string for a specified value. Returns the text of the found value. If no match is found, it returns null

    Ex:-

  • var pat=new RegExp("e"); document.write(pat.exec("The best things in life are free")); Since there is an "e" in the string, the output of the code above will be: e


Methods of the regexp object2

Methods of the RegExp Object

compile()

  • The compile() method is used to change the RegExp.

  • compile() can change both the search pattern, and add or remove the second parameter.

    Ex:- var pat=new RegExp("e"); document.write(pat.test("The best things in life are free"));

    pat.compile("d");

    document.write(pat.test("The best things in life are free"));

  • Since there is an "e" in the string, but not a "d", the output of the code above will be: truefalse


Javascript objects

JavaScript Objects

  • JavaScript supports built in objects like the Math, String or Date object. All these objects provide some functions, which can be called for some processing.

  • In addition to these built-in objects, you can also create your own.

  • An object is just a special kind of data, with a collection of properties and methods.

    Ex:- A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc.


Javascript objects1

JavaScript Objects

Properties

  • The syntax for accessing a property of an object is:

  • objName.propName

    Ex:-personObj.firstname="John"

    document.write(personObj.firstname)

    Output: John

    Methods

  • An object can also contain methods.

  • objName.methodName()


Javascript objects2

JavaScript Objects

Creating Own Objects:-

personObj=new Object();

personObj.firstname="John";

personObj.lastname="Doe";

Create a template of an object:-

function person(firstname,lastname,age,eyecolor)

{

this.firstname=firstname;

this.lastname=lastname;

this.age=age;

this.eyecolor=eyecolor;

}

  • Once you have the template, you can create new instances of the object, like this:

  • myFather=new person("John","Doe",50,"blue");


Conclusion

Conclusion

  • some of the key concepts of JavaScript are pretty standard across most programming/scripting languages - concepts such as operators, variables and functions.

  • Thus by adding JavaScript to HTML pages , makes the website more dynamic and interactive


Assignment for the class

Assignment for the class

  • Login page

  • Email address: should be a valid email address

  • Password: should contain atleast 1 number and 1 special character


References

References

  • http://www.w3schools.com/

  • http://www.topxml.com/javascript/default.asp

  • http://www.quackit.com/javascript/tutorial/javascript_summary.cfm


  • Login