Movatterモバイル変換


[0]ホーム

URL:


Bhavsingh Maloth, profile picture
Uploaded byBhavsingh Maloth
847 views

Web programming UNIT II by Bhavsingh Maloth

This document provides notes on web programming unit 2 prepared by Bhavsingh Maloth. It discusses the history and objectives of JavaScript, defining it as a scripting language used to add interactivity to HTML pages. JavaScript can be divided into core, client-side, and server-side components. Core JavaScript is the basis of the language, while client-side JavaScript supports browser controls and user interactions. Server-side JavaScript makes the language useful on web servers. The document also provides examples of how to write text, insert scripts, and use variables in JavaScript.

Embed presentation

Downloaded 22 times
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHObjectives:Understand JavaScript.Understand Objects in JavaScript.Understand DHTML with JavaScript.History Of #
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHThe main usage of JavaScript is to add various Web functionalities, Web form validations,browser detections, creation of cookies and so on. JavaScript, along with VBScript, is one ofthe most popular scripting languages and that is why it is supported by almost all webbrowsers available today like Firefox, Opera or the most famous Internet Explorer.JavaScript is the most popular scripting language on the internet, and works in all majorbrowsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminarycompilation) Everyone can use JavaScript without purchasing a licenseAre Java and JavaScript the same?NO!Java and JavaScript are two completely different languages in both concept and design!What can a JavaScript do?JavaScript gives HTML designers a programming tool - HTML authors are normally notprogrammers, but JavaScript is a scripting language with a very simple syntax! Almostanyone can put small "snippets" of code into their HTML pagesJavaScript can put dynamic text into an HTML page - A JavaScript statement like this:document.write("<h1>" + name + "</h1>") can write a variable text into an HTML pageJavaScript can react to events - A JavaScript can be set to execute when somethinghappens, like when a page has finished loading or when a user clicks on an HTML element2
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHJavaScript can read and write HTML elements - A JavaScript can read and change thecontent of an HTML elementJavaScript can be used to validate data - A JavaScript can be used to validate form databefore it is submitted to a server. This saves the server from extra processingJavaScript can be used to detect the visitor's browser - A JavaScript can be used to detectthe visitor's browser, and - depending on the browser - load another page specificallydesigned for that browserJavaScript can be used to create cookies - A JavaScript can be used to store and retrieveinformation on the visitor's computerThe Real Name is ECMAScriptJavaScript's official name is ECMAScript.ECMAScript is developed and maintained by the ECMA organization.ECMA-262 is the official JavaScript standard.The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and hasappeared in all Netscape and Microsoft browsers since 1996.The development of ECMA-262 started in 1996, and the first edition of was adopted by theECMA General Assembly in June 1997.The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998.The HTML <script> tag is used to insert a JavaScript into an HTML page.JavaScriptJavaScript is a scripting language used to enable programmatic access to objects withinother applications. It is primarily used in the form of client-side JavaScript for thedevelopment of dynamic websites. JavaScript is a dialect of the ECMAScript standard and ischaracterized as a dynamic, weakly typed, prototype-based language with first-classfunctions. JavaScript was influenced by many languages and was designed to look like Java,but to be easier for non-programmers to work with.JavaScript-specificJavaScript is officially managed by Mozilla, and new language features are addedperiodically. However, only some non-Mozilla "JavaScript" engines support these newfeatures: conditional catch clauses property getter and setter functions3
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH iterator protocol adopted from Python shallow generators/coroutines also adopted from Python array comprehensions and generator expressions also adopted from Python proper block scope via new let keyword array and object destructuring (limited form of pattern matching) concise function expressions (function(args) expr)Use in web pages The primary use of JavaScript is to write functions that are embedded in or included fromHTML pages and interact with the Document Object Model (DOM) of the page. Somesimple examples of this usage are: Opening or popping up a new window with programmatic control over the size, position, andattributes of the new window (i.e. whether the menus, toolbars, etc. are visible). Validation of web form input values to make sure that they will be accepted before they aresubmitted to the server. Changing images as the mouse cursor moves over them: This effect is often used to draw theuser's attention to important links displayed as graphical elements.JavaScript and Java A common misconception is that JavaScript is similar or closely related to Java; this is notso. Both have a C-like syntax, are object-oriented, are typically sandboxed and are widelyused in client-side Web applications, but the similarities end there. Java has static typing;JavaScript's typing is dynamic (meaning a variable can hold an object of any type and cannotbe restricted). Java is loaded from compiled bytecode; JavaScript is loaded as humanreadable code. C is their last common ancestor language. Nonetheless, JavaScript was designed with Java's syntax and standard library in mind. Inparticular, all Java keywords are reserved in JavaScript, JavaScript's standard library followsJava's naming conventions, and JavaScript's Math and Date classes are based on those fromJava 1.0.JAVASCRIPT HOW TO .. .EXAMPLES4
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHWrite textHow to write text on a pageHOW TO PUT A JAVASCRIPT INTO AN HTML DOCUMENT<html><head></head><body><script type="text/javascript">document.write("Hello World!")</script></body></html>And it produces this output:Hello World!To insert a script in an HTML document, use the <script> tag. Use the type attribute to define thescripting language.<script type="text/javascript">Then comes the #
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHENDING STATEMENTS WITH A SEMICOLON?With the traditional programming languages C++ and Java, each code statement has to end witha semicolon.Many programmers continue this habit when writing JavaScript, but in general, semicolons areoptional and are required only if you want to put more than one statement on a single line.HOW TO HANDLE OLDER BROWSERSOlder browsers that do not support scripts will display the script as page content. To preventthem from doing this, you can use the HTML comment tag:<script type="text/javascript"><!-some statements//--></script>The two forward slashes in front of the end of comment line (//) are a JavaScript commentsymbol, and prevent the JavaScript from trying to compile the line.Note that you can't put // in front of the first comment line (like //<!--), because older browserwill display it. Funny? Yes ! But that's the way it is.JAVASCRIPT VARIABLESAN EXAMPLE OF VARIABLE USEVariableVariables are used to store data. This example shows you how:<html><body><script type="text/javascript">var name = "WECT"document.write(name)document.write("<h1>"+name+"</h1>>")</script>This example declares a variable, assigns a value to it, and then displays the variable.<P> Then thevariable is displayed one more time, only this time within a heading element.</body></html>6
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHVARIABLESA variable is a "container" for information you want to store. A variable's value can changeduring the script. You can refer to a variable by name to see its value or to change its value.Rules for Variable names:Variable names are case sensitiveThey must begin with a letter or the underscore characterDECLARE A VARIABLEYou can create a variable with the var statement:var strname = some valueYou can also create a variable without the var statement:strname = some valueASSIGN A VALUE TO A VARIABLEYou assign a value to a variable like this:var strname = "Hege"Or like this:strname = "Hege"The variable name is on the left side of the expression and the value you want to assign to thevariable is on the right. Now the variable "strname" has the value "Hege".LIFETIME OF VARIABLES When you declare a variable within a function, the variable can only be accessed withinthat function. When you exit the function, the variable is destroyed. These variables arecalled local variables. You can have local variables with the same name in differentfunctions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it.The lifetime of these variables starts when they are declared, and ends when the page isclosed.7
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHWHERE TO PUT YOUR JAVASCRIPT IN A WEB PAGEScripts in a page will be executed immediately while the page loads into the browser. This is notalways what we want. Sometimes we want to execute a script when a page loads, other timeswhen a user triggers an event.Scripts in the head section: Scripts to be executed when they are called, or when an event istriggered, go in the head section. When you place a script in the head section, you will ensurethat the script is loaded before anyone uses it.<html><head><script type="text/javascript">some statements</script></head>Scripts in the body section: Scripts to be executed when the page loads go in the body section.When you place a script in the body section it generates the content of the page.<html><head></head><body><script type="text/javascript">some statements</script></body>Scripts in both the body and the head section: You can place an unlimited number of scriptsin your document, so you can have scripts in both the body and the head section.<html><head><script type="text/javascript">some statements</script></head><body><script type="text/javascript">some statements</script></body>HOW TO RUN AN EXTERNAL JAVASCRIPT8
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH Sometimes you might want to run the same script on several pages, without writing thescript on each and every page. To simplify this you can write a script in an external file, and save it with a .js fileextension, like this:document.write("This script is external")Save the external file as xxx.js.Note: The external script cannot contain the <script> tagNow you can call this script, using the "src" attribute, from any of your pages:<html><head></head><body><script src="xxx.js"></script></body></html>Remember to place the script exactly where you normally would write the script.EXAMPLESHead sectionScripts that contain functions go in the head section of the document. Then we can be sure thatthe script is loaded before the function is called.<html><head><script type="text/javascript">function message(){alert("This alert box was called with the onload event")}</script></head><body></body></html>Body sectionExecute a script that is placed in the body section.<html><body>9
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH<script type="text/javascript">document.write("This message is written when the page loads")</script></body></html>External scriptHow to access an external script.<html><head><script src="xxx.js"></script></head><body>In this case, the script is in an external script file called "xxx.js".</body></html>Conditional statements are used to perform different actions based on different conditions.JAVASCRIPT CONDITIONAL STATEMENTSCONDITIONAL STATEMENTSVery often when you write code, you want to perform different actions for different decisions.You can use conditional statements in your code to do this.In JavaScript we have three conditional statements:if statement - use this statement if you want to execute a set of code when a condition istrueif...else statement - use this statement if you want to select one of two sets of lines toexecuteswitch statement - use this statement if you want to select one of many sets of lines toexecuteIF AND IF...ELSE STATEMENTYou should use the if statement if you want to execute some code if a condition is true.10
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHSYNTAXif (condition){code to be executed if condition is true}EXAMPLE//If the time on your browser is less than 10,//you will get a "Good morning" greeting.<script type="text/javascript">var d=new Date()var time=d.getHours()if (time<10){document.write("<b>Good morning</b>")}</script>Notice that there is no ..else.. in this syntax. You just tell the code to execute some code if thecondition is true.If you want to execute some code if a condition is true and another code if a condition is false,use the if....else statement.SYNTAXif (condition){code to be executed if condition is true}else{code to be executed if condition is false}EXAMPLE//If the time on your browser is less than 10,//you will get a "Good morning" greeting.//Otherwise you will get a "Good day" greeting.<script type="text/javascript">var d = new Date()var time = d.getHours()if (time < 10){document.write("Good morning!")11
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH}else{document.write("Good day!")}</script>SWITCH STATEMENTYou should use the Switch statement if you want to select one of many blocks of code to beexecuted.SYNTAXswitch (expression){case label1:code to be executed if expression = label1breakcase label2:code to be executed if expression = label2breakdefault:code to be executedif expression is differentfrom both label1 and label2}This is how it works: First we have a single expression (most often a variable), that is evaluatedonce. The value of the expression is then compared with the values for each case in the structure.If there is a match, the block of code associated with that case is executed. Use break to preventthe code from running into the next case automatically.EXAMPLE//You will receive a different greeting based//on what day it is. Note that Sunday=0,//Monday=1, Tuesday=2, etc.<script type="text/javascript">var d=new Date()theDay=d.getDay()switch (theDay){case 5:document.write("Finally Friday")break12
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHcase 6:document.write("Super Saturday")breakcase 0:document.write("Sleepy Sunday")breakdefault:document.write("I'm looking forward to this weekend!")}</script>CONDITIONAL OPERATOR JavaScript also contains a conditional operator that assigns a value to a variable based onsome condition.SYNTAXvariablename=(condition)?value1:value2EXAMPLEgreeting=(visitor=="PRES")?"Dear President ":"Dear " If the variable visitor is equal to PRES, then put the string "Dear President " in thevariable named greeting. If the variable visitor is not equal to PRES, then put the string"Dear " into the variable named greeting.EXAMPLESIf statementHow to write an If statement. Use this statement if you want to execute a set of code if aspecified condition is true.<html><body><script type="text/javascript">var d = new Date()var time = d.getHours()if (time < 10){13
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHdocument.write("<b>Good Morning</b>")}</script><p>This example demonstrates the If statement. <p>If the time on your browser is less than 10, youwill get a "Good Morning" greeting.</body></html>If...else statementHow to write an If...Else statement. Use this statement if you want to execute one set of code ifthe condition is true and another set of code if the condition is false.<html><body><script type="text/javascript">var d = new Date()var time = d.getHours()if (time < 10){document.write("<b>Good Morning</b>")}else{document.write("<b>Good Day</b>")}</script><p>This example demonstrates the If ... Else statement. <p>If the time on your browser is less than10, you will get a "Good Morning" greeting. Otherwise you will get a "Good Day" greeting</body></html>Random linkThis example demonstrates a link, when you click on the link it will take you to W3Schools.comOR to W3AppML.com. There is a 50% chance for each of them.<html><body><script type="text/javascript">var r = Math.random()if (r>0.5){document.write("<a href='http://www.w3schools.com'>Learn Web Development!<a>")}else{14
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHdocument.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!<a>")}</script><p>This example demonstrates the Math.random() method. <p>The Hyperlink included in the pagedepends on the state of a random variable.</body></html>Switch statementHow to write a switch statement. Use this statement if you want to select one of many blocks ofcode to execute.<html><body><script type="text/javascript">var d = new Date()var theDay = d.getDay()switch (theDay){case 5:document.write("<b>Finally Friday</b>")breakcase 6:document.write("<b>Super Saturday</b>")breakcase 0:document.write("<b>Sleepy Sunday</b>")breakdefault:document.write("<b>Looking Forward to the Weekend</b>")}</script><p>This example demonstrates the switch statement. <p>The text presented depends on the day ofthe week (0=Sunday, 1=Monday, 2=Tuesday, etc.)</body></html>POP BOXEXAlert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed.Syntax15
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHalert("sometext");Example<html><head><script type="text/javascript">function show_alert(){alert("I am an alert box!"); }</script></head><body><input type="button" onclick="show_alert()" value="Show alert box" /></body></html>16
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHConfirm 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.Syntaxconfirm("sometext");Example<html><head><script type="text/javascript">function show_confirm(){ var r=confirm("Press a button");if (r==true){document.write("You pressed OK!");}else{ document.write("You pressed Cancel!"); } }</script></head><body><input type="button" onclick="show_confirm()" value="Show confirm box" /></body></html>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 afterentering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the boxreturns null.Syntaxprompt("sometext","defaultvalue");Example<html><head><script type="text/javascript">function show_prompt(){17
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHvar name=prompt("Please enter your name","Harry Potter");if (name!=null && name!=""){document.write("Hello " + name + "! How are you today?");}}</script></head><body><input type="button" onclick="show_prompt()" value="Show prompt box" /></body></html>JavaScript Functions To keep the browser from executing a script when the page loads, you can put your scriptinto a function. A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page (or even from other pages if thefunction is embedded in an external .js file). Functions can be defined both in the <head> and in the <body> section of a document.However, to assure that a function is read/loaded by the browser before it is called, it couldbe wise to put functions in the <head> section.This is JavaScript's method to alert the user.alert("here goes the message")HOW TO DEFINE A FUNCTION: To create a function you define its name, any values ("arguments"), and some statements:function myfunction(argument1,argument2,etc){some statements} A function with no arguments must include the parentheses:18
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHfunction myfunction(){some statements} Arguments are variables that will be used in the function. The variable values will be thevalues passed on by the function call. By placing functions in the head section of the document, you make sure that all the codein the function has been loaded before the function is called.Some functions return a value to the calling expressionfunction result(a,b){c=a+breturn c}HOW TO CALL A FUNCTION: A function is not executed before it is called.You can call a function containing arguments:myfunction(argument1,argument2,etc)or without arguments:myfunction()THE RETURN STATEMENT: Functions that will return a result must use the "return" statement. This statementspecifies the value which will be returned to where the function was called from. Say youhave a function that returns the sum of two numbers:function total(a,b){result=a+breturn result}When you call this function you must send two arguments with it:sum=total(2,3)19
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHThe returned value from the function (5) will be stored in the variable called sum.EXAMPLESFunctionHow to call a function.<html><head><script type="text/javascript">function myfunction(){alert("HELLO")}</script></head><body><form><input type="button" onclick="myfunction()" value="Call function"></form><p>By pressing the button, a function will be called. The function will alert a message.</body></html>Function with argumentsHow to pass a variable to a function, and use the variable value in the function.<html><head><script type="text/javascript">function myfunction(txt){alert(txt)}</script></head><body><form><input type="button" onclick="myfunction('Hello')" value="Call function"></form><p>By pressing the button, a function will be called. The function will alert using the argument text.</body></html>20
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHFunction with arguments 2How to pass variables to a function, and use these variable values in the function.<html><head><script type="text/javascript">function myfunction(txt){alert(txt)}</script></head><body><form><input type="button" onclick="myfunction('Good Morning')" value="In the Morning"><input type="button" onclick="myfunction('Good Evening')" value="In the Evening"></form><p>By pressing a button, a function will be called. The function will alert using the argument passedto it.</body></html>Function that returns a valueHow to let the function return a value.<html><head><script type="text/javascript">function myfunction(){return ("Hello, have a nice day!")}</script></head><body><script type="text/javascript">document.write(myFunction())</script><p>The function returns text.</body></html>A function with arguments, that returns a valueHow to let the function find the sum of 2 arguments and return the result.21
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH<html><head><script type="text/javascript">function total(numberA,numberB){return numberA + numberB}</script></head><body><script type="text/javascript">document.write(total(2,3))</script><p>The script in the body section calls a function with two arguments: 2 and 3.<p>The function returns the sum of these two arguments.</body></html>JAVASCRIPT OBJECT JavaScript is an Object Oriented Programming (OOP) language. A programminglanguage can be called object-oriented if it provides four basic capabilities to developers:Encapsulation . the capability to store related information, whether data or methods,together in an objectAggregation . the capability to store one object inside of another objectInheritance . the capability of a class to rely upon another class (or number of classes)for some of its properties and methodsPolymorphism . the capability to write one function or method that works in a variety ofdifferent waysObjects are composed of attributes. If an attribute contains a function, it is considered tobe a method of the object otherwise, the attribute is considered a property.OBJECT PROPERTIES: Object properties can be any of the three primitive data types, or any of the abstract datatypes, such as another object. Object properties are usually variables that are used22
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHinternally in the object's methods, but can also be globally visible variables that are usedthroughout the page.The syntax for adding a property to an object is:objectName.objectProperty = propertyValue;EXAMPLE:Following is a simple example to show how to get a document title using "title" property ofdocument object:var str = document.title;OBJECT METHODS: The methods are functions that let the object do something or let something be done to it.There is little difference between a function and a method, except that a function is astandalone unit of statements and a method is attached to an object and can bereferenced by the this keyword. Methods are useful for everything from displaying the contents of the object to the screento performing complex mathematical operations on a group of local properties andparameters.EXAMPLE:Following is a simple example to show how to use write() method of document object to writeany content on the document:document.write("This is test");USER-DEFINED OBJECTS:23
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH All user-defined objects and built-in objects are descendants of an object called Object.THE NEW OPERATOR: The new operator is used to create an instance of an object. To create an object, the newoperator is followed by the constructor method.In the following example, the constructor methods are Object(), Array(), and Date(). Theseconstructors are built-in JavaScript functions.var employee = new Object();var books = new Array("C++", "Perl", "Java");var day = new Date("August 15, 1947"); THE OBJECT() CONSTRUCTOR: A constructor is a function that creates and initializes an object. JavaScript provides aspecial constructor function called Object() to build the object. The return value of theObject() constructor is assigned to a variable. The variable contains a reference to the new object. The properties assigned to the objectare not variables and are not defined with the var keyword.EXAMPLE 1:This example demonstrates how to create an object:<html><head><title>User-defined objects</title><script type="text/javascript">var book = new Object(); // Create the objectbook.subject = "Perl"; // Assign properties to the objectbook.author = "Mohtashim";</script></head><body>24
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH<script type="text/javascript">document.write("Book name is : " + book.subject + "<br>");document.write("Book author is : " + book.author + "<br>");</script></body></html>EXAMPLE 2: This example demonstrates how to create an object with a User-Defined Function. Herethis keyword is used to refer to the object that has been passed to a function:<html><head><title>User-defined objects</title><script type="text/javascript">function book(title, author){this.title = title;this.author = author;}</script></head><body><script type="text/javascript">var myBook = new book("Perl", "Mohtashim");document.write("Book title is : " + myBook.title + "<br>");document.write("Book author is : " + myBook.author + "<br>");</script></body></html>JAVASCRIPT NATIVE OBJECTS:Javascript - StringsJavascript - Date25
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHJavascript - BooleanJavascript - MathJavascript - Date:The Date object is a datatype built into the JavaScript language. Date objects are created with thenew Date( ) as shown below.SYNTAX:Here are different variant of Date() constructor:newnewnewnewDate( )Date(milliseconds)Date(datestring)Date(year,month,date[,hour,minute,second,millisecond ])Note: Paramters in the brackets are always optionalHere is the description of the parameters:No Argument: With no arguments, the Date( ) constructor creates a Date object set tothe current date and time.milliseconds: When one numeric argument is passed, it is taken as the internal numericrepresentation of the date in milliseconds, as returned by the getTime( ) method. Forexample, passing the argument 5000 creates a date that represents five seconds pastmidnight on 1/1/70.datestring:When one string argument is passed, it is a string representation of a date, inthe format accepted by the Date.parse( ) method.7 agruments: To use the last form of constructor given above, Here is the description ofeach argument:1. year: Integer value representing the year. For compatibility (in order to avoid theY2K problem), you should always specify the year in full; use 1998, rather than98.2. month: Integer value representing the month, beginning with 0 for January to 11for December.3. date: Integer value representing the day of the month.4. hour: Integer value representing the hour of the day (24-hour scale).5. minute: Integer value representing the minute segment of a time reading.6. second: Integer value representing the second segment of a time reading.7. millisecond: Integer value representing the millisecond segment of a timereading.DATE PROPERTIES:26
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHHere is a list of each property and their description.PropertyDescriptionconstructorSpecifies the function that creates an object's prototype.prototypeThe prototype property allows you to add properties and methods to an object.DATE METHODS:Here is a list of each method and its description.MethodDescriptionDate()Returns today's date and timegetDate()Returns the day of the month for the specified date according to localtime.getDay()Returns the day of the week for the specified date according to localtime.getFullYear()Returns the year of the specified date according to local time.getHours()Returns the hour in the specified date according to local time.getMilliseconds()Returns the milliseconds in the specified date according to local time.getMinutes()Returns the minutes in the specified date according to local time.getMonth()Returns the month in the specified date according to local time.getSeconds()Returns the seconds in the specified date according to local time.getTime()Returns the numeric value of the specified date as the number ofmilliseconds since January 1, 1970, 00:00:00 UTC.27
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHgetTimezoneOffset()Returns the time-zone offset in minutes for the current locale.getUTCDate()Returns the day (date) of the month in the specified date accordingto universal time.getUTCDay()Returns the day of the week in the specified date according touniversal time.getUTCFullYear()Returns the year in the specified date according to universal time.getUTCHours()Returns the hours in the specified date according to universal time.getUTCMilliseconds()Returns the milliseconds in the specified date according to universaltime.getUTCMinutes()Returns the minutes in the specified date according to universaltime.getUTCMonth()Returns the month in the specified date according to universal time.getUTCSeconds()Returns the seconds in the specified date according to universal time.getYear()Deprecated - Returns the year in the specified date according tolocal time. Use getFullYear instead.setDate()Sets the day of the month for a specified date according to local time.setFullYear()Sets the full year for a specified date according to local time.setHours()Sets the hours for a specified date according to local time.setMilliseconds()Sets the milliseconds for a specified date according to local time.setMinutes()Sets the minutes for a specified date according to local time.setMonth()Sets the month for a specified date according to local time.setSeconds()Sets the seconds for a specified date according to local time.28
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHsetTime()Sets the Date object to the time represented by a number ofmilliseconds since January 1, 1970, 00:00:00 UTC.setUTCDate()Sets the day of the month for a specified date according to universaltime.setUTCFullYear()Sets the full year for a specified date according to universal time.setUTCHours()Sets the hour for a specified date according to universal time.setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time.setUTCMinutes()Sets the minutes for a specified date according to universal time.setUTCMonth()Sets the month for a specified date according to universal time.setUTCSeconds()Sets the seconds for a specified date according to universal time.setYear()Deprecated - Sets the year for a specified date according to localtime. Use setFullYear instead.toDateString()Returns the "date" portion of the Date as a human-readable string.toGMTString()Deprecated - Converts a date to a string, using the Internet GMTconventions. Use toUTCString instead.toLocaleDateString()Returns the "date" portion of the Date as a string, using the currentlocale's conventions.toLocaleFormat()Converts a date to a string, using a format string.toLocaleString()Converts a date to a string, using the current locale's conventions.toLocaleTimeString()Returns the "time" portion of the Date as a string, using the currentlocale's conventions.toSource()Returns a string representing the source for an equivalent Dateobject; you can use this value to create a new object.29
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHtoString()Returns a string representing the specified Date object.toTimeString()Returns the "time" portion of the Date as a human-readable string.toUTCString()Converts a date to a string, using the universal time convention.valueOf()Returns the primitive value of a Date object.Example on Date():DateReturns today's date including date, month, and year. Note that the getMonth method returns 0 inJanuary, 1 in February etc. So add 1 to the getMonth method to display the correct date.<html><body><script type="text/javascript">var d = new Date()document.write(d.getDate())document.write(".")document.write(d.getMonth() + 1)document.write(".")document.write(d.getFullYear())</script></body></html>TimeReturns the current local time including hour, minutes, and seconds. To return the GMT time usegetUTCHours, getUTCMinutes etc.<html><body><script type="text/javascript">var d = new Date()document.write(d.getHours())document.write(".")30
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHdocument.write(d.getMinutes() + 1)document.write(".")document.write(d.getSeconds())</script></body></html>Set dateYou can also set the date or time into the date object, with the setDate, setHour etc. Note that inthis example, only the FullYear is set.<html><body><script type="text/javascript">var d = new Date()d.setFullYear("1990")document.write(".")</script></body></html>UTC timeThe getUTCDate method returns the Universal Coordinated Time which is the time set by theWorld Time Standard.<html><body><script type="text/javascript">var d = new Date()document.write(d.getUTCHours())document.write(".")document.write(d.getUTCMinutes() + 1)document.write(".")document.write(d.getUTCSeconds())</script></body></html>Display weekdayA simple script that allows you to write the name of the current day instead of the number. Notethat the array object is used to store the names, and that Sunday=0, Monday=1 etc.<html><body><script type="text/javascript">31
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHvar d = new Date()var weekday=newArray("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")document.write("Today is " + weekday[d.getDay()])</script></body></html>Display full dateHow to write a complete date with the name of the day and the name of the month.<html><body><script type="text/javascript">var d = new Date()var weekday=newArray("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")var monthname=newArray("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")document.write(weekday[d.getDay()] + " ")document.write(d.getDate() + ". ")document.write(monthname[d.getMonth()] + " ")document.write(d.getFullYear())</script></body></html>Display timeHow to display the time on your pages. Note that this script is similar to the Time exampleabove, only this script writes the time in an input field. And it continues writing the time onetime per second.<html><body><script type="text/javascript">var timer = nullfunction stop(){clearTimeout(timer)}function start(){var time = new Date()32
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHvar hours = time.getHours()minutes=((minutes < 10) ? "0" : "") + minutesvar seconds = time.getSeconds()seconds=((seconds < 10) ? "0" : "") + secondsvar clock = hours + ":" + minutes + ":" + secondsdocument.forms[0].display.value = clocktimer = setTimeout("start()",1000)}</script></body></html>JAVASCRIPT - THE STRING OBJECT:SYNTAX:Creating a String object:var val = new String(string);The string parameter is series of characters that has been properly encoded.STRING PROPERTIES:Here is a list of each property and their description.PropertyDescriptionconstructorReturns a reference to the String function that created the object.lengthReturns the length of the string.prototypeThe prototype property allows you to add properties and methods to an object.EXAMPLE: STRING LENGTH33
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHSTRING METHODSHere is a list of each method and its description.MethodDescriptioncharAt()Returns the character at the specified index.charCodeAt()Returns a number indicating the Unicode value of the character at the givenindex.concat()Combines the text of two strings and returns a new string.indexOf()Returns the index within the calling String object of the first occurrence ofthe specified value, or -1 if not found.lastIndexOf()Returns the index within the calling String object of the last occurrence ofthe specified value, or -1 if not found.localeCompare()Returns a number indicating whether a reference string comes before orafter or is the same as the given string in sort order.34
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHmatch()Used to match a regular expression against a string.replace()Used to find a match between a regular expression and a string, and toreplace the matched substring with a new substring.search()Executes the search for a match between a regular expression and aspecified string.slice()Extracts a section of a string and returns a new string.split()Splits a String object into an array of strings by separating the string intosubstrings.substr()Returns the characters in a string beginning at the specified locationthrough the specified number of characters.substring()Returns the characters in a string between two indexes into the string.toLocaleLowerCase()The characters within a string are converted to lower case while respectingthe current locale.toLocaleUpperCase()The characters within a string are converted to upper case while respectingthe current locale.toLowerCase()Returns the calling string value converted to lower case.toString()Returns a string representing the specified object.toUpperCase()Returns the calling string value converted to uppercase.valueOf()Returns the primitive value of the specified object.Example:FINDING A STRING IN A STRING35
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHThe indexOf() method returns the position (as a number) of the first found occurrence of aspecified text inside a string:EXAMPLEvar str="Hello world, welcome to the universe.";var n=str.indexOf("welcome");// index starts from “0”MATCHING CONTENTThe match() method can be used to search for a matching content in a string:EXAMPLEvar str="Hello world!";document.write(str.match("world") + "<br>");document.write(str.match("World") + "<br>");document.write(str.match("world!"));REPLACING CONTENTThe replace() method replaces a specified value with another value in a string.EXAMPLEstr="Please visit Microsoft!"var n=str.replace("Microsoft","gpcet");UPPER CASE AND LOWER CASEA string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():EXAMPLEvar txt="Hello World!";// Stringvar txt1=txt.toUpperCase(); // txt1 is txt converted to upper36
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHvar txt2=txt.toLowerCase(); // txt2 is txt converted to lowerJAVASCRIPT - THE MATH OBJECTThe math object provides you properties and methods for mathematical constants and functions.Unlike the other global objects, Math is not a constructor. All properties and methods of Mathare static and can be called by using Math as an object without creating it.SYNTAX:Here is the simple syntax to call properties and methods of Math.var pi_val = Math.PI;var sine_val = Math.sin(30);MATH PROPERTIES:Here is a list of each property and their description.PropertyDescriptionEEuler's constant and the base of natural logarithms, approximately 2.718.LN2Natural logarithm of 2, approximately 0.693.LN10Natural logarithm of 10, approximately 2.302.LOG2EBase 2 logarithm of E, approximately 1.442.LOG10EBase 10 logarithm of E, approximately 0.434.PIRatio of the circumference of a circle to its diameter, approximately 3.14159.SQRT1_2Square root of 1/2; equivalently, 1 over the square root of 2, approximately0.707.37
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHSQRT2Square root of 2, approximately 1.414.MATH METHODSHere is a list of each method and its description.MethodDescriptionabs()Returns the absolute value of a number.acos()Returns the arccosine (in radians) of a number.asin()Returns the arcsine (in radians) of a number.atan()Returns the arctangent (in radians) of a number.atan2()Returns the arctangent of the quotient of its arguments.ceil()Returns the smallest integer greater than or equal to a number.cos()Returns the cosine of a number.exp()Returns EN, where N is the argument, and E is Euler's constant, the base of thenatural logarithm.floor()Returns the largest integer less than or equal to a number.log()Returns the natural logarithm (base E) of a number.max()Returns the largest of zero or more numbers.min()Returns the smallest of zero or more numbers.pow()Returns base to the exponent power, that is, base exponent.random()Returns a pseudo-random number between 0 and 1.38
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHround()Returns the value of a number rounded to the nearest integer.sin()Returns the sine of a number.sqrt()Returns the square root of a number.tan()Returns the tangent of a number.toSource()Returns the string "Math".EXAMPLE:RoundHow to round a specified number to the nearest whole number<html><body><script type="text/javascript">document.write(Math.round(7.25))</script></body></html>Random numberThe random method returns a random number between 0 and 1<html><body><script type="text/javascript">document.write(Math.random())</script></body></html>Random number from 0-10How to write a random number from 0 to 10, using the round and the random method.39
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH<html><body><script type="text/javascript">no=Math.random()*10document.write(Math.floor(no))</script></body></html>Max numberHow to test which of two numbers, has the highest value.<html><body><script type="text/javascript">document.write(Math.max(2,4))</script></body></html>Min numberHow to test which of two numbers, has the lowest value.<html><body><script type="text/javascript">document.write(Math.min(2,4))</script></body></html>JAVASCRIPT - THE BOOLEAN OBJECTThe Boolean object represents two values either "true" or "false".SYNTAX:Creating a boolean object:var val = new Boolean(value);40
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHIf value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), theobject has an initial value of false.BOOLEAN PROPERTIES:Here is a list of each property and their description.PropertyDescriptionconstructorReturns a reference to the Boolean function that created the object.prototypeThe prototype property allows you to add properties and methods to an object.BOOLEAN METHODSHere is a list of each method and its description.MethodDescriptiontoSource()Returns a string containing the source of the Boolean object; you can use thisstring to create an equivalent object.toString()Returns a string of either "true" or "false" depending upon the value of theobject.valueOf()Returns the primitive value of the Boolean object.JAVA SCRIPT EVENTS:WHAT IS AN EVENT ?JavaScript's interaction with HTML is handled through events that occur when the user orbrowser manipulates a page.41
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHHTML 4 STANDARD EVENTSThe standard HTML 4 events are listed here for your reference. Here script indicates aJavascript function to be executed agains that event.EventValueDescriptiononchangescriptScript runs when the element changesonsubmitscriptScript runs when the form is submittedonresetscriptScript runs when the form is resetonselectscriptScript runs when the element is selectedonblurscriptScript runs when the element loses focusonfocusscriptScript runs when the element gets focusonkeydownscriptScript runs when key is pressedonkeypressscriptScript runs when key is pressed and releasedonkeyupscriptScript runs when key is releasedonclickscriptScript runs when a mouse clickondblclickscriptScript runs when a mouse double-clickonmousedownscriptScript runs when mouse button is pressedonmousemovescriptScript runs when mouse pointer movesonmouseoutscriptScript runs when mouse pointer moves out of an42
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHelementonmouseoverscriptScript runs when mouse pointer moves over an elementonmouseupscriptScript runs when mouse button is releasedONCLICK EVENT TYPE:This is the most frequently used event type which occurs when a user clicks mouse left button.You can put your validation, warning etc against this event type.EXAMPLE:<html><head><script type="text/javascript"><!-function sayHello() {alert("Hello World")}//--></script></head><body><input type="button" onclick="sayHello()" value="Say Hello" /></body></html>ONSUBMIT EVENT TYPE:Another most important event type is onsubmit. This event occurs when you try to submit aform. So you can put your form validation against this event type.Here is simple example showing its usage. Here we are calling a validate() function beforesubmitting a form data to the webserver. If validate() function returns true the form will besubmitted otherwise it will not submit the data.EXAMPLE:43
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH<html><head><script type="text/javascript"><!-function validation() {all validation goes here.........return either true or false}//--></script></head><body><form method="POST" action="t.cgi" onsubmit="return validate()">.......<input type="submit" value="Submit" /></form></body></html>ONMOUSEOVER AND ONMOUSEOUT:These two event types will help you to create nice effects with images or even with text aswell. The onmouseover event occurs when you bring your mouse over any element and theonmouseout occurs when you take your mouse out from that element.EXAMPLE:Following example shows how a division reacts when we bring our mouse in that division:<html><head><script type="text/javascript"><!-function over() {alert("Mouse Over");}function out() {alert("Mouse Out");}//--></script></head><body><div onmouseover="over()" onmouseout="out()"><h2> This is inside the division </h2></div></body>44
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH</html>List of Javascript Programs:JAVASCRIPT PROGRAMS WITH EXAMPLESFibonacci Series JavaScript Program (for beginners)This is a simple JavaScript example program for fibonacci sequence.<body><script type="text/javascript">var a=0,b=1,c;document.write("Fibonacci");while (b<=10){document.write(c);document.write("<br/>");c=a+b;a=b;b=c;}</script></body></html>Copy Text JavaScript Program (for beginners)This is simple JavaScript Program with example to Copy Text from Different Field.<45
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHhtml><head><title>Copy text</title></head><body><center><h2>Copy text from different field</h2><p><input type="text" style="color: #FF0080;background-color: #C9C299" id="field1" value="GoodMorning"><input type="text" style="color: #FF0080;background-color: #C9C299" id="field2"><button style="background-color: #E799A3" onclick="document.getElementById('field2').value =document.getElementById('field1').value">Click to Copy Text</p></center></body></html>Form Validation JavaScript Program (for beginners)This is a simple JavaScript form validation program with example.<html><head><script type="text/javascript">function sub(){if(document.getElementById("t1").value == "")alert("Please enter your name");else if(document.getElementById("t2").value == "")alert("Please enter a password");else if(document.getElementById("t2").value != document.getElementById("t3").value)alert("Please enter correct password");else if(document.getElementById("t4").value == "")alert("Please enter your address");elsealert("Form has been submitted");}</script></head><body><form><p align="center">46
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHUser Name:<input type="text" id="t1"><br><br>Password:<input type="text" id="t2"><br><br>Confirm Password:<input type="text" id="t3"><br><br>Address:<textarea rows="2" cols="25" id="t4"></textarea><br><br><input type="button" value="Submit" onclick="sub()"><input type="reset" value="Clear All"></p></form></body></html>JavaScript Popup Window Program (for beginners)This is a simple JavaScript example program to generate confirm box.<html><head><script type="text/javaScript">function see(){var c= confirm("Click OK to see Google Homepage or CANCEL to see Bing Homepage");if (c== true){window.location="http://www.google.co.in/";}else{window.location="http://www.bing.com/";}}</script></head><body><center><form><input type="button" value="Click to chose either Google or Bing" onclick="see()"></form></center></body></html>47
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHPalindrome JavaScript Program (for beginners)This is a simple JavaScript palindrome program with example.<html><body><script type="text/javascript">function Palindrome() {var revStr = "";var str = document.getElementById("str").value;var i = str.length;for(var j=i; j>=0; j--) {revStr = revStr+str.charAt(j);}if(str == revStr) {alert(str+" -is Palindrome");} else {alert(str+" -is not a Palindrome");}}</script><form >Enter a String/Number: <input type="text" id="str" name="string" /><br /><input type="submit" value="Check" onclick="Palindrome();"/></form></body></html>Check Odd/Even Numbers JavaScript Program (forbeginners)This is a simple JavaScript program to check odd or even numbers with example.<html><head><script type="text/javascript">48
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHvar n = prompt("Enter a number to find odd or even", "Type your number here");n = parseInt(n);if (isNaN(n)){alert("Please Enter a Number");}else if (n == 0){alert("The number is zero");}else if (n%2){alert("The number is odd");}else{alert("The number is even");}</script></head><body></body></html>Simple Switch Case JavaScript Program (for beginners)This is a simple switch case JavaScript example program for beginners..<html><head><script type="text/javascript">var n=prompt("Enter a number between 1 and 7");switch (n){case (n="1"):document.write("Sunday");break;case (n="2"):document.write("Monday");break;case (n="3"):document.write("Tuesday");49
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTHbreak;case (n="4"):document.write("Wednesday");break;case (n="5"):document.write("Thursday");break;case (n="6"):document.write("Friday");break;case (n="7"):document.write("Saturday");break;default:document.write("Invalid Weekday");break}</script></head></html>ALL THE BEST50
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH51

Recommended

PDF
Web Programming UNIT VIII notes
PDF
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
PDF
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
PPTX
Introduction to python
RTF
Hack language
PDF
web programming UNIT VIII python by Bhavsingh Maloth
PPT
Programming Languages An Intro
PPTX
Python | What is Python | History of Python | Python Tutorial
PPTX
Go programing language
PDF
Research paper on python by Rj
PDF
Fundamentals of python
PDF
Lets Go - An introduction to Google's Go Programming Language
DOCX
Source vs object code
PPT
Prelims Coverage for Int 213
PPTX
Mark asoi ppt
PPTX
Copmuter Languages
PDF
Mastering Regex in Perl
PPTX
Types Of Coding Languages: A Complete Guide To Master Programming
PPT
Introduction to python
PPTX
Programming
PPTX
Fundamentals of programming final santos
PPTX
Comparison of Programming Platforms
PDF
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
PPTX
Insight into progam execution ppt
PDF
C lecture notes new
PDF
Python Intro
DOCX
resume
PDF
Python Introduction
PPT
JAVA SCRIPT
DOC
Basics java scripts

More Related Content

PDF
Web Programming UNIT VIII notes
PDF
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
PDF
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
PPTX
Introduction to python
RTF
Hack language
PDF
web programming UNIT VIII python by Bhavsingh Maloth
PPT
Programming Languages An Intro
PPTX
Python | What is Python | History of Python | Python Tutorial
Web Programming UNIT VIII notes
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
Introduction to python
Hack language
web programming UNIT VIII python by Bhavsingh Maloth
Programming Languages An Intro
Python | What is Python | History of Python | Python Tutorial

What's hot

PPTX
Go programing language
PDF
Research paper on python by Rj
PDF
Fundamentals of python
PDF
Lets Go - An introduction to Google's Go Programming Language
DOCX
Source vs object code
PPT
Prelims Coverage for Int 213
PPTX
Mark asoi ppt
PPTX
Copmuter Languages
PDF
Mastering Regex in Perl
PPTX
Types Of Coding Languages: A Complete Guide To Master Programming
PPT
Introduction to python
PPTX
Programming
PPTX
Fundamentals of programming final santos
PPTX
Comparison of Programming Platforms
PDF
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
PPTX
Insight into progam execution ppt
PDF
C lecture notes new
PDF
Python Intro
DOCX
resume
PDF
Python Introduction
Go programing language
Research paper on python by Rj
Fundamentals of python
Lets Go - An introduction to Google's Go Programming Language
Source vs object code
Prelims Coverage for Int 213
Mark asoi ppt
Copmuter Languages
Mastering Regex in Perl
Types Of Coding Languages: A Complete Guide To Master Programming
Introduction to python
Programming
Fundamentals of programming final santos
Comparison of Programming Platforms
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
Insight into progam execution ppt
C lecture notes new
Python Intro
resume
Python Introduction

Similar to Web programming UNIT II by Bhavsingh Maloth

PPT
JAVA SCRIPT
DOC
Basics java scripts
PPTX
Java script Basic
PDF
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
PDF
JS BASICS JAVA SCRIPT SCRIPTING
PPT
Introduction to JavaScript
PPTX
JavaScript New Tutorial Class XI and XII.pptx
PPT
Java script
PPT
Java script
PPTX
Javascript 01 (js)
PPTX
Java script introduction
PPT
JS-Slides-1hgvhfhgftgfvujguyghvhjbjbnnhg
DOC
2javascript web programming with JAVA script
DOCX
Javascript tutorial
PPT
java script programming slide 1 from tn state
PPT
JS-Slides-1 (1).ppt vbefgvsdfgdfgfggergertgrtgrtgt
PPT
JS-Slides_for_begineers_javascript-1.ppt
PPT
basics of javascript and fundamentals ppt
PPT
Javascript overview and introduction to js
PPTX
JavaScript_III.pptx
JAVA SCRIPT
Basics java scripts
Java script Basic
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
JS BASICS JAVA SCRIPT SCRIPTING
Introduction to JavaScript
JavaScript New Tutorial Class XI and XII.pptx
Java script
Java script
Javascript 01 (js)
Java script introduction
JS-Slides-1hgvhfhgftgfvujguyghvhjbjbnnhg
2javascript web programming with JAVA script
Javascript tutorial
java script programming slide 1 from tn state
JS-Slides-1 (1).ppt vbefgvsdfgdfgfggergertgrtgrtgt
JS-Slides_for_begineers_javascript-1.ppt
basics of javascript and fundamentals ppt
Javascript overview and introduction to js
JavaScript_III.pptx

More from Bhavsingh Maloth

PPT
web programming Unit VI PPT by Bhavsingh Maloth
PDF
web programming Unit VIII complete about python by Bhavsingh Maloth
PDF
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
PDF
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
PDF
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
PDF
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
PPT
Xml dom & sax by bhavsingh maloth
PDF
Polytechnic jan 6 2012
PDF
Appscpolytechniclecturersg.s.paper2007
PDF
Appsc poly key 2013
PDF
Appscpolytechniclecturersg.s.paper2007
PDF
Appsc poly key 2013
PDF
98286173 government-polytechnic-lecturer-exam-paper-2012
PPT
Unit vii wp ppt
PDF
Unit VI
PDF
Wp unit III
PDF
Wp unit 1 (1)
web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VIII complete about python by Bhavsingh Maloth
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
Xml dom & sax by bhavsingh maloth
Polytechnic jan 6 2012
Appscpolytechniclecturersg.s.paper2007
Appsc poly key 2013
Appscpolytechniclecturersg.s.paper2007
Appsc poly key 2013
98286173 government-polytechnic-lecturer-exam-paper-2012
Unit vii wp ppt
Unit VI
Wp unit III
Wp unit 1 (1)

Recently uploaded

PPTX
PURPOSIVE SAMPLING IN EDUCATIONAL RESEARCH RACHITHRA RK.pptx
PPTX
York "Collaboration for Research Support at U-M Library"
PDF
Projecte de la porta de la classe de primer A: Mar i cel.
PDF
IMANI Africa files RTI request seeking full disclosure on 2026 SIM registrati...
PDF
The Drift Principle: When Information Accelerates Faster Than Minds Can Compress
PPTX
The Cell & Cell Cycle-detailed structure and function of organelles.pptx
PPTX
How to Configure Push & Pull Rule in Odoo 18 Inventory
PDF
Analyzing the data of your initial survey
PPTX
Campfens "The Data Qualify Challenge: Publishers, institutions, and funders r...
PDF
Toward Massive, Ultrareliable, and Low-Latency Wireless Communication With Sh...
PDF
NAVIGATE PHARMACY CAREER OPPORTUNITIES.pdf
PPTX
2025-2026 History in your Hands Class 4 December 2025 January 2026 .pptx
PPTX
How to use search_read method in Odoo 18
PPTX
Semester 6 UNIT 2 Dislocation of hip.pptx
PDF
FAMILY ASSESSMENT FORMAT - CHN practical
PPTX
Accounting Skills Paper-II (Registers of PACs and Credit Co-operative Societies)
PDF
M.Sc. Nonchordates Complete Syllabus PPT | All Important Topics Covered
PPTX
Semester 6 unit 2 Atopic dermatitis.pptx
PPTX
How to Manage Package Reservation in Odoo 18 Inventory
PPTX
Cost of Capital - Cost of Equity, Cost of debenture, Cost of Preference share...
PURPOSIVE SAMPLING IN EDUCATIONAL RESEARCH RACHITHRA RK.pptx
York "Collaboration for Research Support at U-M Library"
Projecte de la porta de la classe de primer A: Mar i cel.
IMANI Africa files RTI request seeking full disclosure on 2026 SIM registrati...
The Drift Principle: When Information Accelerates Faster Than Minds Can Compress
The Cell & Cell Cycle-detailed structure and function of organelles.pptx
How to Configure Push & Pull Rule in Odoo 18 Inventory
Analyzing the data of your initial survey
Campfens "The Data Qualify Challenge: Publishers, institutions, and funders r...
Toward Massive, Ultrareliable, and Low-Latency Wireless Communication With Sh...
NAVIGATE PHARMACY CAREER OPPORTUNITIES.pdf
2025-2026 History in your Hands Class 4 December 2025 January 2026 .pptx
How to use search_read method in Odoo 18
Semester 6 UNIT 2 Dislocation of hip.pptx
FAMILY ASSESSMENT FORMAT - CHN practical
Accounting Skills Paper-II (Registers of PACs and Credit Co-operative Societies)
M.Sc. Nonchordates Complete Syllabus PPT | All Important Topics Covered
Semester 6 unit 2 Atopic dermatitis.pptx
How to Manage Package Reservation in Odoo 18 Inventory
Cost of Capital - Cost of Equity, Cost of debenture, Cost of Preference share...

Web programming UNIT II by Bhavsingh Maloth

  • 1.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHObjectives:Understand JavaScript.Understand Objects in JavaScript.Understand DHTML with JavaScript.History Of #"https://www.slideshare.net/slideshow/web-programming-unit-ii/28624053#2">WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHThe main usage of JavaScript is to add various Web functionalities, Web form validations,browser detections, creation of cookies and so on. JavaScript, along with VBScript, is one ofthe most popular scripting languages and that is why it is supported by almost all webbrowsers available today like Firefox, Opera or the most famous Internet Explorer.JavaScript is the most popular scripting language on the internet, and works in all majorbrowsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminarycompilation) Everyone can use JavaScript without purchasing a licenseAre Java and JavaScript the same?NO!Java and JavaScript are two completely different languages in both concept and design!What can a JavaScript do?JavaScript gives HTML designers a programming tool - HTML authors are normally notprogrammers, but JavaScript is a scripting language with a very simple syntax! Almostanyone can put small "snippets" of code into their HTML pagesJavaScript can put dynamic text into an HTML page - A JavaScript statement like this:document.write("<h1>" + name + "</h1>") can write a variable text into an HTML pageJavaScript can react to events - A JavaScript can be set to execute when somethinghappens, like when a page has finished loading or when a user clicks on an HTML element2
  • 3.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHJavaScript can read and write HTML elements - A JavaScript can read and change thecontent of an HTML elementJavaScript can be used to validate data - A JavaScript can be used to validate form databefore it is submitted to a server. This saves the server from extra processingJavaScript can be used to detect the visitor's browser - A JavaScript can be used to detectthe visitor's browser, and - depending on the browser - load another page specificallydesigned for that browserJavaScript can be used to create cookies - A JavaScript can be used to store and retrieveinformation on the visitor's computerThe Real Name is ECMAScriptJavaScript's official name is ECMAScript.ECMAScript is developed and maintained by the ECMA organization.ECMA-262 is the official JavaScript standard.The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and hasappeared in all Netscape and Microsoft browsers since 1996.The development of ECMA-262 started in 1996, and the first edition of was adopted by theECMA General Assembly in June 1997.The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998.The HTML <script> tag is used to insert a JavaScript into an HTML page.JavaScriptJavaScript is a scripting language used to enable programmatic access to objects withinother applications. It is primarily used in the form of client-side JavaScript for thedevelopment of dynamic websites. JavaScript is a dialect of the ECMAScript standard and ischaracterized as a dynamic, weakly typed, prototype-based language with first-classfunctions. JavaScript was influenced by many languages and was designed to look like Java,but to be easier for non-programmers to work with.JavaScript-specificJavaScript is officially managed by Mozilla, and new language features are addedperiodically. However, only some non-Mozilla "JavaScript" engines support these newfeatures: conditional catch clauses property getter and setter functions3
  • 4.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH iterator protocol adopted from Python shallow generators/coroutines also adopted from Python array comprehensions and generator expressions also adopted from Python proper block scope via new let keyword array and object destructuring (limited form of pattern matching) concise function expressions (function(args) expr)Use in web pages The primary use of JavaScript is to write functions that are embedded in or included fromHTML pages and interact with the Document Object Model (DOM) of the page. Somesimple examples of this usage are: Opening or popping up a new window with programmatic control over the size, position, andattributes of the new window (i.e. whether the menus, toolbars, etc. are visible). Validation of web form input values to make sure that they will be accepted before they aresubmitted to the server. Changing images as the mouse cursor moves over them: This effect is often used to draw theuser's attention to important links displayed as graphical elements.JavaScript and Java A common misconception is that JavaScript is similar or closely related to Java; this is notso. Both have a C-like syntax, are object-oriented, are typically sandboxed and are widelyused in client-side Web applications, but the similarities end there. Java has static typing;JavaScript's typing is dynamic (meaning a variable can hold an object of any type and cannotbe restricted). Java is loaded from compiled bytecode; JavaScript is loaded as humanreadable code. C is their last common ancestor language. Nonetheless, JavaScript was designed with Java's syntax and standard library in mind. Inparticular, all Java keywords are reserved in JavaScript, JavaScript's standard library followsJava's naming conventions, and JavaScript's Math and Date classes are based on those fromJava 1.0.JAVASCRIPT HOW TO .. .EXAMPLES4
  • 5.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHWrite textHow to write text on a pageHOW TO PUT A JAVASCRIPT INTO AN HTML DOCUMENT<html><head></head><body><script type="text/javascript">document.write("Hello World!")</script></body></html>And it produces this output:Hello World!To insert a script in an HTML document, use the <script> tag. Use the type attribute to define thescripting language.<script type="text/javascript">Then comes the #"https://www.slideshare.net/slideshow/web-programming-unit-ii/28624053#6">WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHENDING STATEMENTS WITH A SEMICOLON?With the traditional programming languages C++ and Java, each code statement has to end witha semicolon.Many programmers continue this habit when writing JavaScript, but in general, semicolons areoptional and are required only if you want to put more than one statement on a single line.HOW TO HANDLE OLDER BROWSERSOlder browsers that do not support scripts will display the script as page content. To preventthem from doing this, you can use the HTML comment tag:<script type="text/javascript"><!-some statements//--></script>The two forward slashes in front of the end of comment line (//) are a JavaScript commentsymbol, and prevent the JavaScript from trying to compile the line.Note that you can't put // in front of the first comment line (like //<!--), because older browserwill display it. Funny? Yes ! But that's the way it is.JAVASCRIPT VARIABLESAN EXAMPLE OF VARIABLE USEVariableVariables are used to store data. This example shows you how:<html><body><script type="text/javascript">var name = "WECT"document.write(name)document.write("<h1>"+name+"</h1>>")</script>This example declares a variable, assigns a value to it, and then displays the variable.<P> Then thevariable is displayed one more time, only this time within a heading element.</body></html>6
  • 7.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHVARIABLESA variable is a "container" for information you want to store. A variable's value can changeduring the script. You can refer to a variable by name to see its value or to change its value.Rules for Variable names:Variable names are case sensitiveThey must begin with a letter or the underscore characterDECLARE A VARIABLEYou can create a variable with the var statement:var strname = some valueYou can also create a variable without the var statement:strname = some valueASSIGN A VALUE TO A VARIABLEYou assign a value to a variable like this:var strname = "Hege"Or like this:strname = "Hege"The variable name is on the left side of the expression and the value you want to assign to thevariable is on the right. Now the variable "strname" has the value "Hege".LIFETIME OF VARIABLES When you declare a variable within a function, the variable can only be accessed withinthat function. When you exit the function, the variable is destroyed. These variables arecalled local variables. You can have local variables with the same name in differentfunctions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it.The lifetime of these variables starts when they are declared, and ends when the page isclosed.7
  • 8.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHWHERE TO PUT YOUR JAVASCRIPT IN A WEB PAGEScripts in a page will be executed immediately while the page loads into the browser. This is notalways what we want. Sometimes we want to execute a script when a page loads, other timeswhen a user triggers an event.Scripts in the head section: Scripts to be executed when they are called, or when an event istriggered, go in the head section. When you place a script in the head section, you will ensurethat the script is loaded before anyone uses it.<html><head><script type="text/javascript">some statements</script></head>Scripts in the body section: Scripts to be executed when the page loads go in the body section.When you place a script in the body section it generates the content of the page.<html><head></head><body><script type="text/javascript">some statements</script></body>Scripts in both the body and the head section: You can place an unlimited number of scriptsin your document, so you can have scripts in both the body and the head section.<html><head><script type="text/javascript">some statements</script></head><body><script type="text/javascript">some statements</script></body>HOW TO RUN AN EXTERNAL JAVASCRIPT8
  • 9.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH Sometimes you might want to run the same script on several pages, without writing thescript on each and every page. To simplify this you can write a script in an external file, and save it with a .js fileextension, like this:document.write("This script is external")Save the external file as xxx.js.Note: The external script cannot contain the <script> tagNow you can call this script, using the "src" attribute, from any of your pages:<html><head></head><body><script src="xxx.js"></script></body></html>Remember to place the script exactly where you normally would write the script.EXAMPLESHead sectionScripts that contain functions go in the head section of the document. Then we can be sure thatthe script is loaded before the function is called.<html><head><script type="text/javascript">function message(){alert("This alert box was called with the onload event")}</script></head><body></body></html>Body sectionExecute a script that is placed in the body section.<html><body>9
  • 10.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH<script type="text/javascript">document.write("This message is written when the page loads")</script></body></html>External scriptHow to access an external script.<html><head><script src="xxx.js"></script></head><body>In this case, the script is in an external script file called "xxx.js".</body></html>Conditional statements are used to perform different actions based on different conditions.JAVASCRIPT CONDITIONAL STATEMENTSCONDITIONAL STATEMENTSVery often when you write code, you want to perform different actions for different decisions.You can use conditional statements in your code to do this.In JavaScript we have three conditional statements:if statement - use this statement if you want to execute a set of code when a condition istrueif...else statement - use this statement if you want to select one of two sets of lines toexecuteswitch statement - use this statement if you want to select one of many sets of lines toexecuteIF AND IF...ELSE STATEMENTYou should use the if statement if you want to execute some code if a condition is true.10
  • 11.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHSYNTAXif (condition){code to be executed if condition is true}EXAMPLE//If the time on your browser is less than 10,//you will get a "Good morning" greeting.<script type="text/javascript">var d=new Date()var time=d.getHours()if (time<10){document.write("<b>Good morning</b>")}</script>Notice that there is no ..else.. in this syntax. You just tell the code to execute some code if thecondition is true.If you want to execute some code if a condition is true and another code if a condition is false,use the if....else statement.SYNTAXif (condition){code to be executed if condition is true}else{code to be executed if condition is false}EXAMPLE//If the time on your browser is less than 10,//you will get a "Good morning" greeting.//Otherwise you will get a "Good day" greeting.<script type="text/javascript">var d = new Date()var time = d.getHours()if (time < 10){document.write("Good morning!")11
  • 12.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH}else{document.write("Good day!")}</script>SWITCH STATEMENTYou should use the Switch statement if you want to select one of many blocks of code to beexecuted.SYNTAXswitch (expression){case label1:code to be executed if expression = label1breakcase label2:code to be executed if expression = label2breakdefault:code to be executedif expression is differentfrom both label1 and label2}This is how it works: First we have a single expression (most often a variable), that is evaluatedonce. The value of the expression is then compared with the values for each case in the structure.If there is a match, the block of code associated with that case is executed. Use break to preventthe code from running into the next case automatically.EXAMPLE//You will receive a different greeting based//on what day it is. Note that Sunday=0,//Monday=1, Tuesday=2, etc.<script type="text/javascript">var d=new Date()theDay=d.getDay()switch (theDay){case 5:document.write("Finally Friday")break12
  • 13.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHcase 6:document.write("Super Saturday")breakcase 0:document.write("Sleepy Sunday")breakdefault:document.write("I'm looking forward to this weekend!")}</script>CONDITIONAL OPERATOR JavaScript also contains a conditional operator that assigns a value to a variable based onsome condition.SYNTAXvariablename=(condition)?value1:value2EXAMPLEgreeting=(visitor=="PRES")?"Dear President ":"Dear " If the variable visitor is equal to PRES, then put the string "Dear President " in thevariable named greeting. If the variable visitor is not equal to PRES, then put the string"Dear " into the variable named greeting.EXAMPLESIf statementHow to write an If statement. Use this statement if you want to execute a set of code if aspecified condition is true.<html><body><script type="text/javascript">var d = new Date()var time = d.getHours()if (time < 10){13
  • 14.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHdocument.write("<b>Good Morning</b>")}</script><p>This example demonstrates the If statement. <p>If the time on your browser is less than 10, youwill get a "Good Morning" greeting.</body></html>If...else statementHow to write an If...Else statement. Use this statement if you want to execute one set of code ifthe condition is true and another set of code if the condition is false.<html><body><script type="text/javascript">var d = new Date()var time = d.getHours()if (time < 10){document.write("<b>Good Morning</b>")}else{document.write("<b>Good Day</b>")}</script><p>This example demonstrates the If ... Else statement. <p>If the time on your browser is less than10, you will get a "Good Morning" greeting. Otherwise you will get a "Good Day" greeting</body></html>Random linkThis example demonstrates a link, when you click on the link it will take you to W3Schools.comOR to W3AppML.com. There is a 50% chance for each of them.<html><body><script type="text/javascript">var r = Math.random()if (r>0.5){document.write("<a href='http://www.w3schools.com'>Learn Web Development!<a>")}else{14
  • 15.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHdocument.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!<a>")}</script><p>This example demonstrates the Math.random() method. <p>The Hyperlink included in the pagedepends on the state of a random variable.</body></html>Switch statementHow to write a switch statement. Use this statement if you want to select one of many blocks ofcode to execute.<html><body><script type="text/javascript">var d = new Date()var theDay = d.getDay()switch (theDay){case 5:document.write("<b>Finally Friday</b>")breakcase 6:document.write("<b>Super Saturday</b>")breakcase 0:document.write("<b>Sleepy Sunday</b>")breakdefault:document.write("<b>Looking Forward to the Weekend</b>")}</script><p>This example demonstrates the switch statement. <p>The text presented depends on the day ofthe week (0=Sunday, 1=Monday, 2=Tuesday, etc.)</body></html>POP BOXEXAlert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed.Syntax15
  • 16.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHalert("sometext");Example<html><head><script type="text/javascript">function show_alert(){alert("I am an alert box!"); }</script></head><body><input type="button" onclick="show_alert()" value="Show alert box" /></body></html>16
  • 17.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHConfirm 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.Syntaxconfirm("sometext");Example<html><head><script type="text/javascript">function show_confirm(){ var r=confirm("Press a button");if (r==true){document.write("You pressed OK!");}else{ document.write("You pressed Cancel!"); } }</script></head><body><input type="button" onclick="show_confirm()" value="Show confirm box" /></body></html>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 afterentering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the boxreturns null.Syntaxprompt("sometext","defaultvalue");Example<html><head><script type="text/javascript">function show_prompt(){17
  • 18.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHvar name=prompt("Please enter your name","Harry Potter");if (name!=null && name!=""){document.write("Hello " + name + "! How are you today?");}}</script></head><body><input type="button" onclick="show_prompt()" value="Show prompt box" /></body></html>JavaScript Functions To keep the browser from executing a script when the page loads, you can put your scriptinto a function. A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page (or even from other pages if thefunction is embedded in an external .js file). Functions can be defined both in the <head> and in the <body> section of a document.However, to assure that a function is read/loaded by the browser before it is called, it couldbe wise to put functions in the <head> section.This is JavaScript's method to alert the user.alert("here goes the message")HOW TO DEFINE A FUNCTION: To create a function you define its name, any values ("arguments"), and some statements:function myfunction(argument1,argument2,etc){some statements} A function with no arguments must include the parentheses:18
  • 19.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHfunction myfunction(){some statements} Arguments are variables that will be used in the function. The variable values will be thevalues passed on by the function call. By placing functions in the head section of the document, you make sure that all the codein the function has been loaded before the function is called.Some functions return a value to the calling expressionfunction result(a,b){c=a+breturn c}HOW TO CALL A FUNCTION: A function is not executed before it is called.You can call a function containing arguments:myfunction(argument1,argument2,etc)or without arguments:myfunction()THE RETURN STATEMENT: Functions that will return a result must use the "return" statement. This statementspecifies the value which will be returned to where the function was called from. Say youhave a function that returns the sum of two numbers:function total(a,b){result=a+breturn result}When you call this function you must send two arguments with it:sum=total(2,3)19
  • 20.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHThe returned value from the function (5) will be stored in the variable called sum.EXAMPLESFunctionHow to call a function.<html><head><script type="text/javascript">function myfunction(){alert("HELLO")}</script></head><body><form><input type="button" onclick="myfunction()" value="Call function"></form><p>By pressing the button, a function will be called. The function will alert a message.</body></html>Function with argumentsHow to pass a variable to a function, and use the variable value in the function.<html><head><script type="text/javascript">function myfunction(txt){alert(txt)}</script></head><body><form><input type="button" onclick="myfunction('Hello')" value="Call function"></form><p>By pressing the button, a function will be called. The function will alert using the argument text.</body></html>20
  • 21.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHFunction with arguments 2How to pass variables to a function, and use these variable values in the function.<html><head><script type="text/javascript">function myfunction(txt){alert(txt)}</script></head><body><form><input type="button" onclick="myfunction('Good Morning')" value="In the Morning"><input type="button" onclick="myfunction('Good Evening')" value="In the Evening"></form><p>By pressing a button, a function will be called. The function will alert using the argument passedto it.</body></html>Function that returns a valueHow to let the function return a value.<html><head><script type="text/javascript">function myfunction(){return ("Hello, have a nice day!")}</script></head><body><script type="text/javascript">document.write(myFunction())</script><p>The function returns text.</body></html>A function with arguments, that returns a valueHow to let the function find the sum of 2 arguments and return the result.21
  • 22.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH<html><head><script type="text/javascript">function total(numberA,numberB){return numberA + numberB}</script></head><body><script type="text/javascript">document.write(total(2,3))</script><p>The script in the body section calls a function with two arguments: 2 and 3.<p>The function returns the sum of these two arguments.</body></html>JAVASCRIPT OBJECT JavaScript is an Object Oriented Programming (OOP) language. A programminglanguage can be called object-oriented if it provides four basic capabilities to developers:Encapsulation . the capability to store related information, whether data or methods,together in an objectAggregation . the capability to store one object inside of another objectInheritance . the capability of a class to rely upon another class (or number of classes)for some of its properties and methodsPolymorphism . the capability to write one function or method that works in a variety ofdifferent waysObjects are composed of attributes. If an attribute contains a function, it is considered tobe a method of the object otherwise, the attribute is considered a property.OBJECT PROPERTIES: Object properties can be any of the three primitive data types, or any of the abstract datatypes, such as another object. Object properties are usually variables that are used22
  • 23.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHinternally in the object's methods, but can also be globally visible variables that are usedthroughout the page.The syntax for adding a property to an object is:objectName.objectProperty = propertyValue;EXAMPLE:Following is a simple example to show how to get a document title using "title" property ofdocument object:var str = document.title;OBJECT METHODS: The methods are functions that let the object do something or let something be done to it.There is little difference between a function and a method, except that a function is astandalone unit of statements and a method is attached to an object and can bereferenced by the this keyword. Methods are useful for everything from displaying the contents of the object to the screento performing complex mathematical operations on a group of local properties andparameters.EXAMPLE:Following is a simple example to show how to use write() method of document object to writeany content on the document:document.write("This is test");USER-DEFINED OBJECTS:23
  • 24.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH All user-defined objects and built-in objects are descendants of an object called Object.THE NEW OPERATOR: The new operator is used to create an instance of an object. To create an object, the newoperator is followed by the constructor method.In the following example, the constructor methods are Object(), Array(), and Date(). Theseconstructors are built-in JavaScript functions.var employee = new Object();var books = new Array("C++", "Perl", "Java");var day = new Date("August 15, 1947"); THE OBJECT() CONSTRUCTOR: A constructor is a function that creates and initializes an object. JavaScript provides aspecial constructor function called Object() to build the object. The return value of theObject() constructor is assigned to a variable. The variable contains a reference to the new object. The properties assigned to the objectare not variables and are not defined with the var keyword.EXAMPLE 1:This example demonstrates how to create an object:<html><head><title>User-defined objects</title><script type="text/javascript">var book = new Object(); // Create the objectbook.subject = "Perl"; // Assign properties to the objectbook.author = "Mohtashim";</script></head><body>24
  • 25.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH<script type="text/javascript">document.write("Book name is : " + book.subject + "<br>");document.write("Book author is : " + book.author + "<br>");</script></body></html>EXAMPLE 2: This example demonstrates how to create an object with a User-Defined Function. Herethis keyword is used to refer to the object that has been passed to a function:<html><head><title>User-defined objects</title><script type="text/javascript">function book(title, author){this.title = title;this.author = author;}</script></head><body><script type="text/javascript">var myBook = new book("Perl", "Mohtashim");document.write("Book title is : " + myBook.title + "<br>");document.write("Book author is : " + myBook.author + "<br>");</script></body></html>JAVASCRIPT NATIVE OBJECTS:Javascript - StringsJavascript - Date25
  • 26.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHJavascript - BooleanJavascript - MathJavascript - Date:The Date object is a datatype built into the JavaScript language. Date objects are created with thenew Date( ) as shown below.SYNTAX:Here are different variant of Date() constructor:newnewnewnewDate( )Date(milliseconds)Date(datestring)Date(year,month,date[,hour,minute,second,millisecond ])Note: Paramters in the brackets are always optionalHere is the description of the parameters:No Argument: With no arguments, the Date( ) constructor creates a Date object set tothe current date and time.milliseconds: When one numeric argument is passed, it is taken as the internal numericrepresentation of the date in milliseconds, as returned by the getTime( ) method. Forexample, passing the argument 5000 creates a date that represents five seconds pastmidnight on 1/1/70.datestring:When one string argument is passed, it is a string representation of a date, inthe format accepted by the Date.parse( ) method.7 agruments: To use the last form of constructor given above, Here is the description ofeach argument:1. year: Integer value representing the year. For compatibility (in order to avoid theY2K problem), you should always specify the year in full; use 1998, rather than98.2. month: Integer value representing the month, beginning with 0 for January to 11for December.3. date: Integer value representing the day of the month.4. hour: Integer value representing the hour of the day (24-hour scale).5. minute: Integer value representing the minute segment of a time reading.6. second: Integer value representing the second segment of a time reading.7. millisecond: Integer value representing the millisecond segment of a timereading.DATE PROPERTIES:26
  • 27.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHHere is a list of each property and their description.PropertyDescriptionconstructorSpecifies the function that creates an object's prototype.prototypeThe prototype property allows you to add properties and methods to an object.DATE METHODS:Here is a list of each method and its description.MethodDescriptionDate()Returns today's date and timegetDate()Returns the day of the month for the specified date according to localtime.getDay()Returns the day of the week for the specified date according to localtime.getFullYear()Returns the year of the specified date according to local time.getHours()Returns the hour in the specified date according to local time.getMilliseconds()Returns the milliseconds in the specified date according to local time.getMinutes()Returns the minutes in the specified date according to local time.getMonth()Returns the month in the specified date according to local time.getSeconds()Returns the seconds in the specified date according to local time.getTime()Returns the numeric value of the specified date as the number ofmilliseconds since January 1, 1970, 00:00:00 UTC.27
  • 28.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHgetTimezoneOffset()Returns the time-zone offset in minutes for the current locale.getUTCDate()Returns the day (date) of the month in the specified date accordingto universal time.getUTCDay()Returns the day of the week in the specified date according touniversal time.getUTCFullYear()Returns the year in the specified date according to universal time.getUTCHours()Returns the hours in the specified date according to universal time.getUTCMilliseconds()Returns the milliseconds in the specified date according to universaltime.getUTCMinutes()Returns the minutes in the specified date according to universaltime.getUTCMonth()Returns the month in the specified date according to universal time.getUTCSeconds()Returns the seconds in the specified date according to universal time.getYear()Deprecated - Returns the year in the specified date according tolocal time. Use getFullYear instead.setDate()Sets the day of the month for a specified date according to local time.setFullYear()Sets the full year for a specified date according to local time.setHours()Sets the hours for a specified date according to local time.setMilliseconds()Sets the milliseconds for a specified date according to local time.setMinutes()Sets the minutes for a specified date according to local time.setMonth()Sets the month for a specified date according to local time.setSeconds()Sets the seconds for a specified date according to local time.28
  • 29.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHsetTime()Sets the Date object to the time represented by a number ofmilliseconds since January 1, 1970, 00:00:00 UTC.setUTCDate()Sets the day of the month for a specified date according to universaltime.setUTCFullYear()Sets the full year for a specified date according to universal time.setUTCHours()Sets the hour for a specified date according to universal time.setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time.setUTCMinutes()Sets the minutes for a specified date according to universal time.setUTCMonth()Sets the month for a specified date according to universal time.setUTCSeconds()Sets the seconds for a specified date according to universal time.setYear()Deprecated - Sets the year for a specified date according to localtime. Use setFullYear instead.toDateString()Returns the "date" portion of the Date as a human-readable string.toGMTString()Deprecated - Converts a date to a string, using the Internet GMTconventions. Use toUTCString instead.toLocaleDateString()Returns the "date" portion of the Date as a string, using the currentlocale's conventions.toLocaleFormat()Converts a date to a string, using a format string.toLocaleString()Converts a date to a string, using the current locale's conventions.toLocaleTimeString()Returns the "time" portion of the Date as a string, using the currentlocale's conventions.toSource()Returns a string representing the source for an equivalent Dateobject; you can use this value to create a new object.29
  • 30.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHtoString()Returns a string representing the specified Date object.toTimeString()Returns the "time" portion of the Date as a human-readable string.toUTCString()Converts a date to a string, using the universal time convention.valueOf()Returns the primitive value of a Date object.Example on Date():DateReturns today's date including date, month, and year. Note that the getMonth method returns 0 inJanuary, 1 in February etc. So add 1 to the getMonth method to display the correct date.<html><body><script type="text/javascript">var d = new Date()document.write(d.getDate())document.write(".")document.write(d.getMonth() + 1)document.write(".")document.write(d.getFullYear())</script></body></html>TimeReturns the current local time including hour, minutes, and seconds. To return the GMT time usegetUTCHours, getUTCMinutes etc.<html><body><script type="text/javascript">var d = new Date()document.write(d.getHours())document.write(".")30
  • 31.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHdocument.write(d.getMinutes() + 1)document.write(".")document.write(d.getSeconds())</script></body></html>Set dateYou can also set the date or time into the date object, with the setDate, setHour etc. Note that inthis example, only the FullYear is set.<html><body><script type="text/javascript">var d = new Date()d.setFullYear("1990")document.write(".")</script></body></html>UTC timeThe getUTCDate method returns the Universal Coordinated Time which is the time set by theWorld Time Standard.<html><body><script type="text/javascript">var d = new Date()document.write(d.getUTCHours())document.write(".")document.write(d.getUTCMinutes() + 1)document.write(".")document.write(d.getUTCSeconds())</script></body></html>Display weekdayA simple script that allows you to write the name of the current day instead of the number. Notethat the array object is used to store the names, and that Sunday=0, Monday=1 etc.<html><body><script type="text/javascript">31
  • 32.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHvar d = new Date()var weekday=newArray("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")document.write("Today is " + weekday[d.getDay()])</script></body></html>Display full dateHow to write a complete date with the name of the day and the name of the month.<html><body><script type="text/javascript">var d = new Date()var weekday=newArray("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")var monthname=newArray("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")document.write(weekday[d.getDay()] + " ")document.write(d.getDate() + ". ")document.write(monthname[d.getMonth()] + " ")document.write(d.getFullYear())</script></body></html>Display timeHow to display the time on your pages. Note that this script is similar to the Time exampleabove, only this script writes the time in an input field. And it continues writing the time onetime per second.<html><body><script type="text/javascript">var timer = nullfunction stop(){clearTimeout(timer)}function start(){var time = new Date()32
  • 33.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHvar hours = time.getHours()minutes=((minutes < 10) ? "0" : "") + minutesvar seconds = time.getSeconds()seconds=((seconds < 10) ? "0" : "") + secondsvar clock = hours + ":" + minutes + ":" + secondsdocument.forms[0].display.value = clocktimer = setTimeout("start()",1000)}</script></body></html>JAVASCRIPT - THE STRING OBJECT:SYNTAX:Creating a String object:var val = new String(string);The string parameter is series of characters that has been properly encoded.STRING PROPERTIES:Here is a list of each property and their description.PropertyDescriptionconstructorReturns a reference to the String function that created the object.lengthReturns the length of the string.prototypeThe prototype property allows you to add properties and methods to an object.EXAMPLE: STRING LENGTH33
  • 34.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHSTRING METHODSHere is a list of each method and its description.MethodDescriptioncharAt()Returns the character at the specified index.charCodeAt()Returns a number indicating the Unicode value of the character at the givenindex.concat()Combines the text of two strings and returns a new string.indexOf()Returns the index within the calling String object of the first occurrence ofthe specified value, or -1 if not found.lastIndexOf()Returns the index within the calling String object of the last occurrence ofthe specified value, or -1 if not found.localeCompare()Returns a number indicating whether a reference string comes before orafter or is the same as the given string in sort order.34
  • 35.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHmatch()Used to match a regular expression against a string.replace()Used to find a match between a regular expression and a string, and toreplace the matched substring with a new substring.search()Executes the search for a match between a regular expression and aspecified string.slice()Extracts a section of a string and returns a new string.split()Splits a String object into an array of strings by separating the string intosubstrings.substr()Returns the characters in a string beginning at the specified locationthrough the specified number of characters.substring()Returns the characters in a string between two indexes into the string.toLocaleLowerCase()The characters within a string are converted to lower case while respectingthe current locale.toLocaleUpperCase()The characters within a string are converted to upper case while respectingthe current locale.toLowerCase()Returns the calling string value converted to lower case.toString()Returns a string representing the specified object.toUpperCase()Returns the calling string value converted to uppercase.valueOf()Returns the primitive value of the specified object.Example:FINDING A STRING IN A STRING35
  • 36.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHThe indexOf() method returns the position (as a number) of the first found occurrence of aspecified text inside a string:EXAMPLEvar str="Hello world, welcome to the universe.";var n=str.indexOf("welcome");// index starts from “0”MATCHING CONTENTThe match() method can be used to search for a matching content in a string:EXAMPLEvar str="Hello world!";document.write(str.match("world") + "<br>");document.write(str.match("World") + "<br>");document.write(str.match("world!"));REPLACING CONTENTThe replace() method replaces a specified value with another value in a string.EXAMPLEstr="Please visit Microsoft!"var n=str.replace("Microsoft","gpcet");UPPER CASE AND LOWER CASEA string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():EXAMPLEvar txt="Hello World!";// Stringvar txt1=txt.toUpperCase(); // txt1 is txt converted to upper36
  • 37.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHvar txt2=txt.toLowerCase(); // txt2 is txt converted to lowerJAVASCRIPT - THE MATH OBJECTThe math object provides you properties and methods for mathematical constants and functions.Unlike the other global objects, Math is not a constructor. All properties and methods of Mathare static and can be called by using Math as an object without creating it.SYNTAX:Here is the simple syntax to call properties and methods of Math.var pi_val = Math.PI;var sine_val = Math.sin(30);MATH PROPERTIES:Here is a list of each property and their description.PropertyDescriptionEEuler's constant and the base of natural logarithms, approximately 2.718.LN2Natural logarithm of 2, approximately 0.693.LN10Natural logarithm of 10, approximately 2.302.LOG2EBase 2 logarithm of E, approximately 1.442.LOG10EBase 10 logarithm of E, approximately 0.434.PIRatio of the circumference of a circle to its diameter, approximately 3.14159.SQRT1_2Square root of 1/2; equivalently, 1 over the square root of 2, approximately0.707.37
  • 38.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHSQRT2Square root of 2, approximately 1.414.MATH METHODSHere is a list of each method and its description.MethodDescriptionabs()Returns the absolute value of a number.acos()Returns the arccosine (in radians) of a number.asin()Returns the arcsine (in radians) of a number.atan()Returns the arctangent (in radians) of a number.atan2()Returns the arctangent of the quotient of its arguments.ceil()Returns the smallest integer greater than or equal to a number.cos()Returns the cosine of a number.exp()Returns EN, where N is the argument, and E is Euler's constant, the base of thenatural logarithm.floor()Returns the largest integer less than or equal to a number.log()Returns the natural logarithm (base E) of a number.max()Returns the largest of zero or more numbers.min()Returns the smallest of zero or more numbers.pow()Returns base to the exponent power, that is, base exponent.random()Returns a pseudo-random number between 0 and 1.38
  • 39.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHround()Returns the value of a number rounded to the nearest integer.sin()Returns the sine of a number.sqrt()Returns the square root of a number.tan()Returns the tangent of a number.toSource()Returns the string "Math".EXAMPLE:RoundHow to round a specified number to the nearest whole number<html><body><script type="text/javascript">document.write(Math.round(7.25))</script></body></html>Random numberThe random method returns a random number between 0 and 1<html><body><script type="text/javascript">document.write(Math.random())</script></body></html>Random number from 0-10How to write a random number from 0 to 10, using the round and the random method.39
  • 40.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH<html><body><script type="text/javascript">no=Math.random()*10document.write(Math.floor(no))</script></body></html>Max numberHow to test which of two numbers, has the highest value.<html><body><script type="text/javascript">document.write(Math.max(2,4))</script></body></html>Min numberHow to test which of two numbers, has the lowest value.<html><body><script type="text/javascript">document.write(Math.min(2,4))</script></body></html>JAVASCRIPT - THE BOOLEAN OBJECTThe Boolean object represents two values either "true" or "false".SYNTAX:Creating a boolean object:var val = new Boolean(value);40
  • 41.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHIf value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), theobject has an initial value of false.BOOLEAN PROPERTIES:Here is a list of each property and their description.PropertyDescriptionconstructorReturns a reference to the Boolean function that created the object.prototypeThe prototype property allows you to add properties and methods to an object.BOOLEAN METHODSHere is a list of each method and its description.MethodDescriptiontoSource()Returns a string containing the source of the Boolean object; you can use thisstring to create an equivalent object.toString()Returns a string of either "true" or "false" depending upon the value of theobject.valueOf()Returns the primitive value of the Boolean object.JAVA SCRIPT EVENTS:WHAT IS AN EVENT ?JavaScript's interaction with HTML is handled through events that occur when the user orbrowser manipulates a page.41
  • 42.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHHTML 4 STANDARD EVENTSThe standard HTML 4 events are listed here for your reference. Here script indicates aJavascript function to be executed agains that event.EventValueDescriptiononchangescriptScript runs when the element changesonsubmitscriptScript runs when the form is submittedonresetscriptScript runs when the form is resetonselectscriptScript runs when the element is selectedonblurscriptScript runs when the element loses focusonfocusscriptScript runs when the element gets focusonkeydownscriptScript runs when key is pressedonkeypressscriptScript runs when key is pressed and releasedonkeyupscriptScript runs when key is releasedonclickscriptScript runs when a mouse clickondblclickscriptScript runs when a mouse double-clickonmousedownscriptScript runs when mouse button is pressedonmousemovescriptScript runs when mouse pointer movesonmouseoutscriptScript runs when mouse pointer moves out of an42
  • 43.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHelementonmouseoverscriptScript runs when mouse pointer moves over an elementonmouseupscriptScript runs when mouse button is releasedONCLICK EVENT TYPE:This is the most frequently used event type which occurs when a user clicks mouse left button.You can put your validation, warning etc against this event type.EXAMPLE:<html><head><script type="text/javascript"><!-function sayHello() {alert("Hello World")}//--></script></head><body><input type="button" onclick="sayHello()" value="Say Hello" /></body></html>ONSUBMIT EVENT TYPE:Another most important event type is onsubmit. This event occurs when you try to submit aform. So you can put your form validation against this event type.Here is simple example showing its usage. Here we are calling a validate() function beforesubmitting a form data to the webserver. If validate() function returns true the form will besubmitted otherwise it will not submit the data.EXAMPLE:43
  • 44.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH<html><head><script type="text/javascript"><!-function validation() {all validation goes here.........return either true or false}//--></script></head><body><form method="POST" action="t.cgi" onsubmit="return validate()">.......<input type="submit" value="Submit" /></form></body></html>ONMOUSEOVER AND ONMOUSEOUT:These two event types will help you to create nice effects with images or even with text aswell. The onmouseover event occurs when you bring your mouse over any element and theonmouseout occurs when you take your mouse out from that element.EXAMPLE:Following example shows how a division reacts when we bring our mouse in that division:<html><head><script type="text/javascript"><!-function over() {alert("Mouse Over");}function out() {alert("Mouse Out");}//--></script></head><body><div onmouseover="over()" onmouseout="out()"><h2> This is inside the division </h2></div></body>44
  • 45.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH</html>List of Javascript Programs:JAVASCRIPT PROGRAMS WITH EXAMPLESFibonacci Series JavaScript Program (for beginners)This is a simple JavaScript example program for fibonacci sequence.<body><script type="text/javascript">var a=0,b=1,c;document.write("Fibonacci");while (b<=10){document.write(c);document.write("<br/>");c=a+b;a=b;b=c;}</script></body></html>Copy Text JavaScript Program (for beginners)This is simple JavaScript Program with example to Copy Text from Different Field.<45
  • 46.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHhtml><head><title>Copy text</title></head><body><center><h2>Copy text from different field</h2><p><input type="text" style="color: #FF0080;background-color: #C9C299" id="field1" value="GoodMorning"><input type="text" style="color: #FF0080;background-color: #C9C299" id="field2"><button style="background-color: #E799A3" onclick="document.getElementById('field2').value =document.getElementById('field1').value">Click to Copy Text</p></center></body></html>Form Validation JavaScript Program (for beginners)This is a simple JavaScript form validation program with example.<html><head><script type="text/javascript">function sub(){if(document.getElementById("t1").value == "")alert("Please enter your name");else if(document.getElementById("t2").value == "")alert("Please enter a password");else if(document.getElementById("t2").value != document.getElementById("t3").value)alert("Please enter correct password");else if(document.getElementById("t4").value == "")alert("Please enter your address");elsealert("Form has been submitted");}</script></head><body><form><p align="center">46
  • 47.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHUser Name:<input type="text" id="t1"><br><br>Password:<input type="text" id="t2"><br><br>Confirm Password:<input type="text" id="t3"><br><br>Address:<textarea rows="2" cols="25" id="t4"></textarea><br><br><input type="button" value="Submit" onclick="sub()"><input type="reset" value="Clear All"></p></form></body></html>JavaScript Popup Window Program (for beginners)This is a simple JavaScript example program to generate confirm box.<html><head><script type="text/javaScript">function see(){var c= confirm("Click OK to see Google Homepage or CANCEL to see Bing Homepage");if (c== true){window.location="http://www.google.co.in/";}else{window.location="http://www.bing.com/";}}</script></head><body><center><form><input type="button" value="Click to chose either Google or Bing" onclick="see()"></form></center></body></html>47
  • 48.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHPalindrome JavaScript Program (for beginners)This is a simple JavaScript palindrome program with example.<html><body><script type="text/javascript">function Palindrome() {var revStr = "";var str = document.getElementById("str").value;var i = str.length;for(var j=i; j>=0; j--) {revStr = revStr+str.charAt(j);}if(str == revStr) {alert(str+" -is Palindrome");} else {alert(str+" -is not a Palindrome");}}</script><form >Enter a String/Number: <input type="text" id="str" name="string" /><br /><input type="submit" value="Check" onclick="Palindrome();"/></form></body></html>Check Odd/Even Numbers JavaScript Program (forbeginners)This is a simple JavaScript program to check odd or even numbers with example.<html><head><script type="text/javascript">48
  • 49.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHvar n = prompt("Enter a number to find odd or even", "Type your number here");n = parseInt(n);if (isNaN(n)){alert("Please Enter a Number");}else if (n == 0){alert("The number is zero");}else if (n%2){alert("The number is odd");}else{alert("The number is even");}</script></head><body></body></html>Simple Switch Case JavaScript Program (for beginners)This is a simple switch case JavaScript example program for beginners..<html><head><script type="text/javascript">var n=prompt("Enter a number between 1 and 7");switch (n){case (n="1"):document.write("Sunday");break;case (n="2"):document.write("Monday");break;case (n="3"):document.write("Tuesday");49
  • 50.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTHbreak;case (n="4"):document.write("Wednesday");break;case (n="5"):document.write("Thursday");break;case (n="6"):document.write("Friday");break;case (n="7"):document.write("Saturday");break;default:document.write("Invalid Weekday");break}</script></head></html>ALL THE BEST50
  • 51.
    WEB PROGRAMMING UNIT-IINOTES: PREPARED BY BHAVSINGH MALOTH51

[8]ページ先頭

©2009-2025 Movatter.jp