Sie sind auf Seite 1von 39

JavaScript - JavaScript Tutorial

JavaScript Tutorials is one of the best Quick reference to the JavaScript. In this JavaScript reference you will find most of the things about java script. JavaScript tutorial is classified into sections with examples. This tutorial is mainly for the beginners but experienced programmer can also learn many things from this JavaScript tutorial series. This JavaScript Tutorial will teach you the fundamentals of JavaScript programming, including the use of the core JavaScript objects and the syntax of the language like statements, conditionals, loops, functions, etc. You will also learn how to immediately put JavaScript to validate forms, calculate values, work with image rollovers and create other user interface. JavaScript is widely used scripting language for mainly validating the user input on the client side (browser). It is also used with the DHTML for creating interactive user interface design. 1. What is JavaScript? This section will introduce with the Java Scripting language. You will learn the benefits of using JavaScript in your programming.

Fundamentals of JavaScript Language


2. Writing Simple JavaScript Example In this section we will learn how to write simple JavaScript program and run in the Internet Explorer. 3. Statements In JavaScript Learn JavaScript Statements. 4. JavaScript Variables and Data types In this section you will learn how to use Variables and Data types in JavaScript. 5. String and Number operations in JavaScript In this section you will learn String and Number operations in JavaScript. 6. Conditional examples (if else - switch case) In JavaScript In this section you will learn the conational statements in JavaScript. 7. Conditions In Java Script Java Script is Netscape's Cross - platform, Object - based Scripting language for Client and Server applications. It is a Case sensitive application. 8. Looping in JavaScript In this section you will learn example to use while, do-while and switch loops in

JavaScript 9. Functions in JavaScript This lesson introduces you with the Function in JavaScript. You will learn how to create and use Functions in JavaScript. 10. Error Handling in JavaScript In this lesson you will learn about error handling in JavaScript. 11. Simple Calculator in JavaScript In this lesson we will write simple Calculator program in JavaScript.

JavaScript as Object Oriented Scripting Language


12. Understanding the Object Oriented Feature of JavaScript In this lesson your will learn the Object Oriented Feature of JavaScript. 13. Classes and Objects After learning this lesson you will be able to use Classes and Object in JavaScript. 14. Form Validation with JavaScript In this lesson you will learn form validation in JavaScript. 15. Dynamically swapping the images with JavaScript In this lesson you will learn how to Dynamically swap the images with JavaScript. 16. JavaScript with Link and Images This lesson shows you how to use JavaScript with Link and Image. o Using onMouseOver and onMouseOut o Using onClick to process clicks on hyperlinks o Having hyperlinks call functions via javascript: URLs o Conditionally navigating the user to a page when they click a link 17. Navigation with combo box and JavaScript In this lesson you will learn how to navigate to some other URL when use selects a link from the combo box. 18. Popup windows with JavaScript In this lesson you will learn how to create popup window using JavaScript. 19. Form validation using Regular Expression in JavaScript In this lesson you will learn form validation using regular expressions.

What is JavaScript? - Definition


In this article you learn the basics of JavaScript and create your first JavaScript program. What is JavaScript? JavaScript is scripting language used for client side scripting. JavaScript developed by Netscape in 1995 as a method for validating forms and providing interactive content to web site. Microsoft and Netscape introduced JavaScript support in their browsers. Benefits of JavaScript Following are the benefits of JavaScript.

associative arrays loosely typed variables regular expressions objects and classes highly evolved date, math, and string libraries W3C DOM support in the JavaScript

Disadvantages of JavaScript

Developer depends on the browser support for the JavaScript There is no way to hide the JavaScript code in case of commercial application

Creating your first JavaScript Program In the first lesson we will create very simple JavaScript program and run in the Internet Explorer. This example simply displays "Welcome to JavaScript World!" message in the browser.

Test JavaScript program from here. Here is the code of JavaScript program: <html> <head> <title>First Java Script</title> <script language="JavaScript"> function sayhello(){ alert("Welcome to JavaScript World!"); } </script> </head> <body> <p><b>Click the following link to run your first java script example</b></p> <p><a href="javascript:sayhello()">Run JavaScript First Program</a></p> </body>

Writing Simple Java Script Program


In this article you learn the basics of JavaScript and create your first JavaScript program. Creating your first JavaScript Program In the last lesson you learned how to create simple java script program. To run the program open the html file in any browser and click on the "Run Java Script First Program". The will display the message box. Here is the screen shot of the browser.

Test JavaScript program from here. Here is the code of JavaScript program: <html> <head>

<title>First Java Script</title> <script language="JavaScript"> function sayhello(){ alert("Welcome to JavaScript World!"); } </script> </head> <body> <p><b>Click the following link to run your first java script example</b></p> <p><a href="javascript:sayhello()">Run JavaScript First Program</a></p> </body> Following is the JavaScript program that will show the message: <script language="JavaScript"> function sayhello(){ alert("Welcome to JavaScript World!"); } </script> The alert() function of the java script displays message.

JavaScript Statements -In this article you learn the basics of JavaScript and create your first JavaScript
program. JavaScript Statement The JavaScript language supported Two type Condition. 1.if statement 2.Function if Statement The if statement is used to make decisions in JavaScript. Boolean operators are also used in along with the if statement. The if statement is the most used features of JavaScript. It is basically the same in JavaScript as it is in other programming languages. Example

<HTML> <HEAD> </HEAD> <SCRIPT language="JavaScript"> <!-var num = 10 if(num == 10) { document.write("<B>Statement!</B><BR>") } //--></SCRIPT> my program successfully completed </BODY> </HTML> Function The function keyword identifies as a function. The parameters in the parenthesis ( ) provide a means of passing values to the function. There can be as many parameters separated by commas as you need. This is perfectly ok to have a function with no parameters. These parameters are variables which are used by the JavaScript statements inside the curly braces { }. The variable keyword is not needed to declare the parameters in a function as variables because they are automatically declared and initialized when the function is called. The function can return a value by using the return keyword. Example

<HTML> <HEAD> </HEAD> <script languane="JavaScript"> function prod(a,b) { var x=a*b return x; } var mul=prod(2,5); document.write("multipication:"+mul); </script> </BODY> </HTML>

Conditional JavaScript if-else Statement The JavaScript Conditional Statement used to different actions and used to based on different conditions. you want to execute some code if a condition is true and another code the condition is not true, use the if....else statement. Example <HTML> <HEAD> </HEAD> script type="text/javascript"> var a = new Date() var time = a.getHours() if (time < 20) { document.write("Good morning!") } else { document.write("Good day!") } </script> </BODY> </HTML>

JavaScript Variables and Data types


JavaScript Variables .Every piece of data is known as a value. When a value is referred in a statement, it is called a literal value. For the same reason people are identified by names as opposed to "human" or "person", literal values can be named in order to make repeated reference to them practical, efficient and readable. These names are called variables. Declaring and Initializing the Variables var num // declare variable, has null value num = 20 // assign a value, null value is replaced //OR var num=20 // declare AND assign value (initialize) var a,b,c,d //multiple variables may be declared simultaneously var a = 5, b = 6, c = 7,d=8 //multiple variables may be initialized simultaneously

Variable Names Variable names cannot contain spaces, begin with a number and can not be used the underscore (_) . JavaScript Variable name can not use any reserved keywords. The two words can either be separated by an underscore (my_variable) or (myVariable). Variable Scope There are two types of Variable scope:1. Globle scope Variable, 2 . Local scope Variable. 1.Globle scope Variable:- A variable declared or initialized outside a function body has a global scope, making it accessible to all other statements within the same document. 2. Globle scope Variable:- A variable declared or initialized within a function body has a local scope, making it accessible only to statements within the same function body. [NOTE:- If a variable is initialized inside a function body but the var keyword is left off, the variable has a global scope and is only accessible after the function containing it is invoked. It is safer to always use the var keyword ] Java script Data type Data Type:- A data type is defined by the value assigned to it . A variable could be a number on one line, then assigned a string value and later be assigned an object reference. JavaScript would change its data type dynamically .It also represent the data's nature. Data is directly treated on those data types and calculate up on the works . There are two types of the data types, As follow:1.Primitive data types 2.Compositive data types 1.Primitive data types:- Primitive data types are the simplest building blocks of a program. There are following types :

numeric:-JavaScript supports both integers and floating point numbers .Integers are whole numbers and it does not support the decimal numbers .Such as : 145 . Floating point numbers are fractional numbers or decimal numbers . Such as : 12.50 string:- String is a collection of characters enclosed in either single quotes and double quotes .If the string starts with a single quotes and it must end with single quotes .If the string starts with a double quotes and it must end with double quotes . Such as : 'Welcome to JavaScript' or "Welcome to JavaScript". Boolean:-Boolean literals are logical values that have only one of two values, true or false. It used to conditional sanitations. Our statements are checked true or false then we use the Boolean variables. null:-The null value represents no value that means strings are empty . undefined:- A variables to be declared but given no any initial value then it runtime error display

Example for :-This example is represent the sum of two floating numbers and print the messages in single quotes and double quotes. <html> <head> <script language="javascript"> function showAlert() { var a=200.40; var b=10.50; var sum=0; sum=a+b; document.write(" sum= "+sum); document.write("\t\tHello\nworld!\n"); document.write('\nWelcome to JavaScript'); } </script> </head> <body> <script language="javascript"> showAlert(); </script> </body> </html>

This program is used to Boolean expression and it display the numbers between 1 to 500 and if user to not enter the number then it display the you did not enter any number. <html> <body> <script type="text/javascript"> var n=0; n=prompt("Enter a number"); document.write("Your entered number is :"+n); if (n>=1 && n<10) document.write("Your entered number is greater than 1 and less than 10"); else if(n>=10 && n<20) document.write("Your entered number is greater than 10

and less than 20"); else if(n>=20 && n<30) document.write("Your entered number is greater than 20 and less than 30"); else if(n>=30 && n<40) document.write("Your entered number is greater than 30 and less than 40"); else if(n>=40 && n<100) document.write("Your entered number is greater than 40 and less than 100"); else if(n>=100 && n<=500) document.write("Your entered number is greater than 100 or less than 500"); else document.write("You did not enter any number!") </script> </body> </html>

String Number Operations in JavaScript


What is String Number Operation? The JavaScript String is a loosely type language. This is not mean that it has no data types that the value of a variable or a JavaScript object property does not need to have a particular type of the value assigned, or that it should be always hold the same type of value. JavaScript also freely type-converts values into a type require by the context of their use. JavaScript being is the loosely typed and willing to type-convert still does not save the programmer from need to the think about the actual type of values that they are dealing with. A very common error in browser scripting. for example, it is to read the value property of a form control into which the user is expected to type a number and then add that value to another number. Because the value properties of form controls are strings if the even then character is sequence they contain represents a number of the attempt to add that string to a value, even if the value happens to be a number, results in the second value being type-converted into a string and concatenated to the end of the first string value from the from control. The problem arises from dual nature of the + operator used for the both numeric addition and string concatenation. which the nature of the operation performed is determined by the context, where only both the operation are numbers to start with the + operator perform addition. Otherwise it converts all of its operands to strings and does concatenation. Converting String: The String most often from the action + Operators. when one of its operators not a number. The easy way of getting the string that results from type-conversion is to

concatenate a value to string. The alternative method of convert a value into a string to pass it is argument to the String constructor called as a function. Exam:Var string Value= String(d); Converting Number: The Converting values to numbers especially to strings numbers, it is an extremely common requirement and many methods can be used. There are any mathematical operation except the concatenation addition operator will force type-conversion. So the conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as subtracting zero or multiplying by one. var numValue = stringValue - 0; var numValue = stringValue * 1; var numValue = stringValue / 1; String in JavaScript The JavaScript language until now we have been focusing on the language constructs of JavaScript: if statements, loops, functions, etc. This primer are going to take a step back and cover the inner workings of some of the native JavaScript objects: Strings, Numbers and Arrays. Example: <html> <head> <Script language="JavaScript"> document.write(' Test'.indexOf('T')); document.write('This '.lastIndexOf('T')); document.write('This is test'.charAt(10)); document.write('This program Test'.length); document.write(' program'.substring(1, 10)); document.write('my exam Test'.substr(7, 10)); document.write('my program'.toUpperCase()); document.write(' first JavaScript program'.toLowerCase()); document.write("<br />") </script> </table> </body> </html>

Array in JavaScript Array is the basically just a list of items. Each item an array can be whatever you want, but they are usually related to one-another. Example: <html> <head> <script language="JavaScript"> var students = ['amar', 'rani', 'vinod', 'susil','santosh']; var suffixes = ['1st', '2nd', '3rd', '4th','5th']; for(var i=0; i<=4; i++) { alert('The '+suffixes[i]+' student is '+students[i]); } </script> </head> </body> </html> JavaScript in Number Operation The numbers is a central task for the many programs. In fact, the desire to automate number operations was the motivation that drove the invention of digital computers decades ago. we will learn how to work with numbers in Java, including arithmetic, conversions, and other numeric operations. Example:

<html> <head> <Script language="JavaScript"> var sum = 10 + 10; sub = 15 - 5; mul = 25 * 5; //multiplication divided = 30 / 5; modulus = 10 % 10; //modulus division document.write("sum:"+sum); document.write("sub:"+sub); document.write("mul:"+mul); document.write("divided:"+divided); document.write("modulus:"+modulus); </script> </head> </body>

</html>

Conditional Examples(if - else- switch case) in JavaScript


About Conditional Statement First of all we write the code after that we want to perform the different actions for different decisions. We can use conditional statements in our code. Conditional statements in JavaScript are used to perform different actions based on different conditions. There are following types of Conditional Statements:

if statement:- It means the condition is true then our writing code is executed other wise our code is not execute . Syntax for the if statement:if ( expression ) { statement1 statement2 } if - else statement:- This statement is used to when the condition is true then our code to execute and when the condition is false then our written code is not execute. Syntax for the if - else statement:if (expression) statement1 else if (expression2) statement2 else statement3 if...else if....else statement -This statement is used to if you want to select one of many blocks of code to be executed . switch statement:-This statement is used to if you want to select one of many blocks of code to be executed. Syntax for the switch statement:switch (expression) { case1: statement1

break case2: statement2 break default: statement3; } This example is if - else statement. It display the first of all the sum of two numbers and check the condition after that it execute the code. <html> <head> <script language="javascript"> function showAlert() { var a=20; var b=10; var sum=0; sum=a+b; document.write(" sum= "+sum); if(sum==3) { document.write("Condition is true"); document.write("This is my first if statement program"); } false { document.write("Condition is false"); document.write(" This is my first if -else statement program"); } } </script> </head> <body> <script language="javascript"> showAlert(); </script> </body> </html>

This example is display to all months in a year for using the switch case:<body> <script type="text/javascript"> var n=0; n=prompt("Enter a number between 1 to 12:") switch(n) { case(n="1"): document.write("January"); break case(n="2"): document.write("Febuary"); break case(n="3"): document.write("March"); break case(n="4"): document.write("April"); break case(n="5"): document.write("May"); break case(n="6"): document.write("June"); break case(n="7"): document.write("July"); break case(n="8"): document.write("August"); break case(n="9"): document.write("September"); break case(n="10"): document.write("October"); break case(n="11"): document.write("November"); break default: document.write("December"); break } </script>

</body>

Conditions In Java Script


About JavaScript Java Script is Netscape's Cross - platform, Object - based Scripting language for Client and Server applications. It is a Case sensitive application. JavaScript programs are usually embedded directly in HTML files. The script executes when the user's browser opens the HTML file. JavaScript is different from the Java language. Now the biggest problem is the imperfect JavaScript implementations that today's browsers offer. Although all major browsers that are version 3.0 or higher include JavaScript code support, they deal with JavaScript differently. In fact, different versions of the same browser handle JavaScript differently. This makes it difficult to create a complicated JavaScript code that work across all browsers. So always check your pages on as many different browsers (and even platforms) as possible. The Simple Example to display the Sum of two Digits :<html> <head> <script language="javascript"> function showAlert() { val1=20; val2=10; document.write("sum="+(val1+val2)); } </script> </head> </body> <script type="text/javascript"> showAlert(); </script> </body> </html>

JavaScript code is embedded in HTML within a <SCRIPT> tag. It can be used to any number of JavaScript Statements. showAlert() is a function to use in JavaScript language. Val1 and Val2 is a data type. we take the value 20 and 10 in val1 and val2. Document.write is also a function to use print the Message and values. The result is 20 display on the Screen.

Looping In Java Script


What is JavaScript loop? The JavaScript loops used to execute the same block or code a specified number of times and while a specified condition. JavaScript loops Very often write code, you want the same block of code to run over and over again in a row. The Instead of adding several almost equal lines in a script we can use loops to perform a task. JavaScript supported Two different type looping :1.The For Loop 2.The while Loop For Loop: The JavaScript for loop is used the know in advance how many times of the script should run. JavaScript loop Use a For loop to run time same block of code a specified the number. Example: <html> <body> <script language="javascript"> var i=0 for (i=0;i<=6;i++) { alert("The number is " + i) } </script> </body> </html>

The while Loop: The while loop is used when the loop to execute and continue executing while the specified condition <html> <body>

<script language="Javascript"> var i=0 while (i<=10) { document.write("serial number" + i) document.write("<br />") i=i+1 } </script> </table> </body> </html> . The do while loop The JavaScript do...while loop is a variant of the while loop. The loop will be always execute a block of code once and then it will repeat the loop as long as the specified condition is true. This loop will be always executed once, even if the condition is false, because the loop code are executed before the condition is tested. Example: <html> <body> <script language="Javascript"> var i=0 do { alert("number" + i) i=i+1 } while (i<3) </script> </table> </body> </html>

The for in: This is not same as the for loop . The javascript for...in loop is used to provide to the enumerate properties of a JavaScript object . This loop only found in JavaScript . This statement in the loop are executed for each property of an object until every property has been accessed.

Example: <html> <head> <Script language="Javascript"> var i; var num= new Array(8,4,5,7,10); for(i in num) { document.write(" " ,num[i]); document.write("<br />") } </script> </head> </body> </html> Javascript looping Break and continue There are two statements supported in javascript used in loop:- Break and continue Break: The JavaScript break command will break the loop and continue executing the code the follows after the loop. Example: <html> <head> <Script language="Javascript"> var i=0 for (i=0;i<=6;i++) { if (i==3){break} alert("number" + i) } </script> </head> </body> </html> Continue: The JavaScript continue command will be break the current loop and continue with the next value. Example

<html> <head> <script language="JavaScript"> var i=0; for (i=0;i<=8;i++) { if (i==4){continue} document.write("value" + i) document.write("</br>") } </script> </head> </body> </html>

JavaScript Functions
What is JavaScript Function? Java script Function is nothing but it is a reusable code-block that is execute when the function is called. Function is defined in the head section of the code. The syntax of JavaScript function is as follows: function fname(prameter1,parameter2, ...) { JavaScript code 1 JavaScript code 2 .... } While defining JavaScript function its important to remember that the keyword function should be in lowercase other wise JavaScript won't understand it as function. If you write function in uppercase the code will generate error. In the JavaScript semicolon is optional but its better to put semi-colon as part of best practices. All the java script code are written inside the curly braces.
Example:

<html> <head> <script language="javascript">

function showmessage(){ alert("How are you"); } </script> </head> <body> <form> <input type="button" value="Click Here!" onclick="showmessage()" > </form> </body> </html> Function starts with the function keyword and code of the function is enclosed in {..} brackets. Functions are written inside the head section of the html document, because function does not execute when the page loads. The alert function displays the message "How are you", when you clicked on the button ("Click Here")..

To test the program click here. What is the use of JavaScript Functions: The java Script Function is very useful in writing the JavaScript code. It is used to group

many JavaScript codes under one name. For example you can write a function to validate email address. Built-in functions JavaScript provides many built in functions that ease the development of JavaScript programs. Here are the list of the built-in JavaScript functions: JavaScript Build in Function alert() confirm() focus() indexOf() prompt() select() write() The prompt() built -in function display the prompt dialog box. Inquiring the user for input. The select() built -in function used to select the pointed object. The write() built in function used to write something on the document. Function Description The alert() built-in function displays the alert dialog box. The confirm() built-in function display the confirmation dialog box. and ask the user to determine from the two option . The focus() built -in function built the pointed object active and put the curser on the text field.

Function arguments: Through variable you can pass argument to function. The out put of the function looks on the arguments given by you . Example: <html> <head> <script language="javascript"> function myfunction(text) { confirm(text) } </script> </head> <body> <form> <input type="button" onclick="myfunction('Do you want to delete it!')" value="Delete">

<input type="button" onclick="myfunction('Do you want to save it!')" value="Save"> </form> </body> </html>

Error Handling in Java Script


In this article you will Learn how to handle error in java script. JavaScript is scripting language used for client side scripting. and error are handling in two ways. *try...catch statement *onerror event Try...Catch Statement The try...catch statement grants an exception in a statement block to be captured and handled. Remember one thing when we write try catch statement. try catch statement should be written in lowercase if we write in upper case program will return error. the try block contains run able code and catch block contains the executable code Syntax: try { //Run some code here } catch(error) { //Handle errors here }

Example: The coming exercise uses a try...catch statement. The example calls a function that retrieves a week name from an array based on the value passed to the function. If the value does not correspond to a week number (1-7), an exception is thrown with the value

InvalidWeekNo and the statements in the catch block set the weekName variable to unknown. <html> <head> <script language="javascript"> function getweekName (wo) { wo=wo-1; // Adjust week number for array index (1=sunday, 7=Saturday) var week=new Array("sunday","monday","Tuesday","Wednesday","Thursday","Friday","Saturday"); if (week[wo] != null) { return week[wo] } else { throw "InvalidweekNo" } } try { // statements to try weekName=getweekName(myweek) // function could throw exception } catch (e) { weekName="unknown" //logMyErrors(e) // pass exception object to error handler alert(e); } </script> </head> </body> <html>

Simple Calculator Application In Java Script


In this article you learn the basics of JavaScript and create your first JavaScript program. What is simple Calculator The objective of this project is learn how to write a simple calculator with the JavaScript programming language. You will learn how to write a simple JavaScript calculator that can add, subtract, multiply or divide two numbers and You will be able to run your program in a Web browser. Web page designers is use JavaScript in many different ways. This is One of the most common is to do field validation in a form. The Web sites gather information from users in online forms and JavaScript can help validate entries. The programmer might validate that a person's age entered into a form falls between 1

and 120. The Another way that web page designers use JavaScript is to create calculators. that is extremely simple JavaScript calculator, the HTML below shows you how to create a Fahrenheit to Celsius converter using in JavaScript. Example <html> <head> <script language="JavaScript"> function temp(form) { var f = parseFloat(form.DegF.value, 10); var T = 0; T = (f - 62.0) * 8.0 / 7.0; form.DegC.value = T; } // done hiding from old browsers --> </script> </head> <body> <FORM> <h2>Fahrenheit to Celsius Converter</h2> Enter a temperature in degrees F: <INPUT NAME="DegF" VALUE="0" MAXLENGTH="25" SIZE=25> <p> Click button to calculate the temperature in degrees T: <INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON onClick=temp(this.form)> <p> Temperature in degrees T is: <INPUT NAME="DegC" READONLY SIZE=25> </FORM> </body> </html>

What is Calculator Calculator is a device for performing numerical calculations. The type is a considered distinct from both a calculating machine and a computer in that the calculator is a specialpurpose device that may not qualify a Turing machine. Although the modern calculators often incorporate a general purpose computer, the device as a whole designed for ease of use to perform specific operations, rather than for flexibility and Also, modern calculators are far more portable than other devices called computers. The morern calculator are

electronically powered and are made by numerous manufacturers in countless shapes and sizes varying from cheap, give-away and credit-card sized models to more sturdy adding machine-like models with built-in printers.

JavaScript Object Oriented Feature


In this article you learn the basics of JavaScript and create your first JavaScript program. What is Object Oriented Feature The ASP.NET and Visual Studio 7.0 are making important contributions to improvement of the web development experience. Unfortunately, this is also a tendency created among developers to limit their interaction with JavaScript. it is Clearly JavaScript is valuable for adding client-side functionality to the web pages. However the ASP.NET programming models suggest that developers produce page layout while emitting clientside JavaScript from ASP.NET controls. As a consequence, this model tends to limit JavaScript to procedural adjuncts. This is rather unfortunate because it severely limits the power of an object-oriented scripting language that developers can be use to write rich and reusable client-side components. JavaScript object oriented will be presented in a series of three type article. The first installments provided background on JavaScript supports the main principles of object-oriented programming. The second part demonstrates how JavaScript constructs can be used to build a class inheritance framework and write scripts supporting in JavaScript class hierarchy. The third and final installment to use the JavaScript class framework to build object-oriented client-side abstractions of ASP.NET user controls. There are Some reasons of way JavaScript Object Oriented Capability are not utilized: There are tendency of client-side operations to be discrete favorite procedures. The ASP.NET programming model are controls suggests limiting JavaScript to the functional adjuncts. Legacy JavaScript lacked key features such as exception handling and inner functions and JavaScript its supported for object- oriented programming . Example: <html> <head> <Script language="JavaScript"> function MyClass() { this.myData = 10; this.myString = "my frist program";

} var myClassObj1 = new MyClass(); var myClassObj2 = new MyClass(); myClassObj1.myData = 20; myClassObj1.myString = "Obj1: my second program"; myClassObj2.myData = 30; myClassObj2.myString = "Obj2: last program"; alert( myClassObj1.myData ); alert( myClassObj1.myString ); alert( myClassObj2.myData ); alert( myClassObj2.myString ); </script> </head> </body> </html> Object-Oriented Programming The Object Oriented programming is a computer programming paradigm. Object Oriented programming is that computer program may be seen as comprising a collection of individual units and objects, that is on each other, as opposed to a traditional view in which a program may be seen as a collection of functions or procedures, or simply as a list of instructions to the computer. Each object is capable of receiving messages, processing data, and sending messages to other objects. The Object-oriented programming is claimed to promote greater flexibility and maintains in programming, and is widely popular in large-scale software engineering. Further the more proponents of OOP claim that Object-Oriented programming is easier to learn those new to computer programming than previous approaches and that the OOP approach is often simpler to develop and to maintain, lending itself to more direct analysis or coding, and understanding of complex situations and procedures than other programming methods. Object: The Object an instance of a class and object is the run-time manifestation of a particular exemplar of a class. The class of dogs which contains breed types, an acceptable exemplar would only be the subclass 'collie'; "Lassie" would then be an object in that subclass. Each object has own data, though the code within a class a subclass or an object may be shared for economy. Thus, object-oriented languages must allow code to be reentrant. Encapsulation The Object-Oriented program using the myclass as defined permits accessibility of its internal data representation as well as this methods and variable names global in scope increasing the risk of name collisions. The Object-Oriented program Encapsulation supports data hiding and the concept of viewing objects as self-contained entities providing services to consumers. The principle of information hiding is the hiding of The design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed. Protecting is a

design decision involves providing a stable interface which shields the remainder of the program from the implementation . Encapsulation is a modern programming languages of the principle of information hiding itself in a number of ways, including encapsulation and polymorphism. Example: <html> <head> <Script language="JavaScript"> function MyClass() { var m_data = 15; var m_text = "indian"; this.SetData = SetData; this.SetText = SetText; this.ShowData = DisplayData; this.ShowText = DisplayText; function DisplayData() { alert( m_data ); } function DisplayText() { alert( m_text ); return; } function SetData( myVal ) { m_data = myVal; } function SetText( myText ) { m_text = myText; } } var Obj1 = new MyClass(); var Obj2 = new MyClass(); Obj1.SetData( 30 ); Obj1.SetText( "Obj1: my cuntry" ); Obj2.SetData( 60 ); Obj2.SetText( "Obj2: my first javaScript progarm" ); Obj1.ShowData(); Obj1.ShowText(); Obj2.ShowData(); Obj2.ShowText();

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

Classes-Objects in JavaScript
In this article you will learn the basics Classes and Objects of JavaScript and create the examples of Classes and Objects in JavaScript . About Object JavaScript is a object oriented programming language so, its variables is depending upon the objects. In object oriented programming language , user create own object to use variables types. An object is a special kinds of data and it contains the properties and methods. JavaScript has several built in objects. Such as: Array, String, Date e.t.c. . Syntax to create an object:object_Name.properties_Name

The example to create an object and display the some results:<html> <body> <script language=javascript"> stuobj=new Object() stuobj.name="vinod" stuobj.roll=10 stuobj.sub="Computer" document.write("Student Name :"+stuobj.name + " Roll no. :- " +stuobj.roll + " Subject :- " +stuobj.sub); </script> </body> </html>

Form Validation With Java Script

In this article you will learn the Validation in JavaScript and your Validation in JavaScript program. JavaScript Java script is used to validate forms, that means checking the proper information are entered to the users in the form fields before submission. It is the most important features in JavaScript . It provide the facilities if we use the validation in the Forms then it automatically check the your entered number or text . If the entered number or text is right then we easily give any type of text or numbers. If we entered the wrong or it means not follows the validations then it automatically represent the given messages . We read the messages and we again try the enter number or text. <html> <head> </head> <body> <FORM name="fm"> Type your first name: <INPUT type="text" name="first"><br> <INPUT type="button" name="dis" value="Display" onClick='alert("You say your name is: "+document.fm.first.value)'> </FORM> </body> </html>

Dynamically Swapping Images with JavaScript


In this article you will learn the numbers Swapping in JavaScript and create a JavaScript program. Image Swapping in JavaScript:- In JavaScript, Numbers Swapping means interchange the numbers to each other . We take two numbers first is (a=10) and second is (b=20). After the swapping the number is change to each other . Such as : a=20 and b=10.

The example of Swapping the numbers in JavaScript:<html> <head>

<script language="javascript"> function showAlert() { var a,b,c; a=10; b=20; document.write("Without Swapping"); document.write("a="+a); document.write("b="+b); c=a; a=b; b=c; document.write("After swpping"); document.write("a="+a); document.write("a="+a); } </script> </head> <body> <script language="javascript"> showAlert(); </script> </body> </html> Output:- Without Swapping a=10 b=20 After Swapping a=20 b=10

Java Script With Links and Images


JavaScript Images The JavaScript image gallery making of Pictures should be quick process. The gap between snapping some pictures and published on the web ought to be a short one. Heres a quick and easy way of making a one-page gallery that uses JavaScript to the load images and their captions on the fly. The identify areas of the HTML document that need to be edited to create JavaScript image swapping.

The JavaScript Describe the difference between the mouse enter events and mouse exit events. JavaScript write the code that will hide the scripts if viewer's browser does not support this feature. Example: <html> <head> <SCRIPT LANGUAGE="JavaScript"> <!-if (document.images) { var pum1 = new Image(); pum1.src = "pussycatdolls_beep.jpg"; var pum2 = new Image(); pum2.src = "AlexanderHaneng_big.jpg"; } function show_rock() { if (document.images) { document["pum"].src = pum2.src; } } function hide_rock() { if (document.images) { document["pum"].src = pum1.src; } } //--> </SCRIPT> </head> <body> <a href="ram.html" onClick="alert('Move the mouse over the rock to see a magnified view.'); return false" onMouseOver="show_rock(); window.status='description of explosiveness scale'; return true" onMouseOut="hide_rock()"> <IMG SRC="pussycatdolls_beep.jpg" align=right ALT="picture of pumice" WIDTH="220" HEIGHT="170" hspace=12 vspace=12 name="pum" border=0></a>

</body> </html> When the mouse cursor over a link (the default image, in this case black) then changes to display a second image in this place. JavaScript Links JavaScript is the one of the more comman on the web today .JavaScript is the image roll over and con be done with the link as very easy and con be done easy images. Example: <html> <body bgcolor="#FFFFFF"> <title>online.net</title> <script language="JavaScript"> function image_over(image_name) { image_name.src = "images/green.gif" } function image_out(image_name) { image_name.src = "images/red.gif" } </script> <img name="image1" src="images/red.gif" border=0> <a href="http://www.roseindia.net/" onmouseover="image_over(image1)" onmouseout="image_out(image1)">online.net</A> </body> </html>

Navigation with Combo box and Java Script


What is JavaScript in Navigation with Combo box? JavaScript is a 2-level combo box menu script. Organize and compact categories into link, all displayed using just one selection box. The navigation that requires absolutely no DHTML or Javascript experience. It is creates any cross-browser, popup or drop-down menu that works alike in all browsers supporting DHTML and in all platforms. The navigation DHTML/JavaScript menus are designed with a treelike approach. Users can tailor their menu by using the Properties Pane or by choosing a predefined appearance

from the Style Gallery. The menu can be either vertical or horizontal, that can be movable, stay visible while scrolling, contain static or animated images, borders, colors, and much more. Once everything is set, you can use the insert-menu-into-Web-page command to add menu in the Web page in a fast and easy manner without any code. Example: <html> <head> <body> <form name="frmdesilt"> <head> <title>Insert Table col using DOM</title> <script language="javascript"> function addcol() { var tbody = document.getElementById("table1").getElementsByTagName("tbody")[0]; var col = document.createElement("TR"); var cell1 = document.createElement("TD"); var inp1 = document.createElement("INPUT"); var combo1=document.createElement("select"); var combo11=document.createElement("option"); var combo12=document.createElement("option"); var combo2=document.createElement("select"); var combo21=document.createElement("option"); var combo22=document.createElement("option"); var inp2=document.createElement("INPUT"); var inp3=document.createElement("INPUT"); inp2.setAttribute("type","text"); inp2.setAttribute("value","no"); inp2.setAttribute("size","4"); inp3.setAttribute("type","text"); inp3.setAttribute("value","amount"); inp3.setAttribute("size","10"); combo1.setAttribute("name","cmbgroup"); combo1.setAttribute("onChange","redirect(this.option.selectedIndex)"); combo11.setAttribute("value","Japan1"); combo11.innerHTML="india--"; combo12.setAttribute("value","kanpur1"); combo12.innerHTML ="kanpur--"; combo2.setAttribute("name","cmbitem"); combo21.setAttribute("value","patna"); combo21.innerHTML="patna--"; combo22.setAttribute("value","Bangolor");

combo22.innerHTML="Bangolor--"; combo1.appendChild(combo11); combo1.appendChild(combo12); combo2.appendChild(combo21); combo2.appendChild(combo22); var cell2 = document.createElement("TD"); cell2.appendChild(combo1); var cell3 = document.createElement("TD"); cell3.appendChild(combo2); var cell4 = document.createElement("TD"); cell4.appendChild(inp2); var cell5 = document.createElement("TD"); cell5.appendChild(inp3); col.appendChild(cell2); col.appendChild(cell3); col.appendChild(cell4); col.appendChild(cell5); tbody.appendChild(col); } </script> </head> <body> <input type="button" value="Add col" size="-6" onClick="addcol();"> <table id="table1"> <tbody> <tr> <th>country-name</th> <th>Item-Name</th> <th>Number</th> <th>Total Amount</th> </tr> <tr> <td><select name="group"> <option>india--</option> </select> </td> <td><select name="item"> <option>calcuta--</option> </select> </td> <td> <input type="text" size="4"> </td>

<td> <input type="text" size="10"> </td> </tr> </tbody> </table> </form> </body> </html>

Popup Window Example in JavaScript


In this article you learn popup Window in java script. Three kinds of popup windows are available in java script. these are

alert confirm prompt

What is JavaScript? JavaScript is scripting language used for client side scripting.

Form Validation using Regular Expressions is JavaScript


What is JavaScript validation using Regular Expressions? The JavaScript Validating user input is the bane of every software developers existence. The developing cross-browser web applications this task becomes even less enjoyable due to the lack of useful intrinsic validation functions in JavaScript. JavaScript 1.2 has incorporated regular expressions. This article I will present a brief tutorial on the basics of regular expressions and then give some examples of how they can be used to simplify data validation. A demonstration page and code library of common validation functions has been included to supplement the examples in the article. Regular Expression: JavaScript regular Expression is the very powerful tool and performing for the patterns matches. the PERL programmers and UNIX shell programmers have enjoyed the benefits of regular expressions for years. Once you are master the pattern language, most validation tasks become trivial. if you perform complex tasks that once required lengthy

procedures with just a few lines of code using regular expressions. The regular Expression two intrinsic objects associated with program. The RegExp object and The Regular Expression object. The RegExp object is the parent in regular expression object. RegExp has a constructor function that is instantiates of the Regular Expression object much like the Date object instantiates an new date. Example: Var RegularExpression = new RegExp("pattern", ["switch"]) The JavaScript has been creating alternet syntax for Regular Expression objects. There are implicitly calls the RegExp constructor function. The syntax for the follows:

var RegularExpression = /pattern/[switch] Using JavaScript Validation The JavaScript validation offered the way if the field contained certain characters using the index Of() method. The character was found, the position of the character was returned as a number. Example: var x = "my program's contents"; var y = x.indexOf("my"); The JavaScript validation using indexOf(), you would be required to write several lines of code, each using the indexOf() to look for all the characters you didn't want to find. If an illegal character is found, an alert box could be flashed asking the user to re-enter their information. The functions use JavaScript 1.0 functionality to examine the text field containing regular text or a text field containing an email address. By passing the contents of the form to the isReady() function using the on Submit event handler, the information is validated before being sent to the server. validation function is the returns true, the ACTION attribute of the form is run. Example: <html> <head> <script language="JavaScript"> function isEmail(string) {

if (!string) return false; var iChars = "*|,\":<>[]{}`\';()&$#%"; for (var i = 0; i < string.length; i++) { if (iChars.indexOf(string.charAt(i)) != -1) return false; } return true; } </script> </head> </html> Using Javascript Regular Expression: The JavaScript 1.2 the way through the power of regular expressions. These expressions, which are offer the same functionality as regular expressions taken from Perl is a very popular scripting language, add the ability to parse form field input in ways that were simply not possible before. The Netscape Navigator 4.0x and Internet Explorer 4, illuminate the power associated with the new additions. It is JavaScript contains a number of new constructors and methods the allow a programmer to string of text using regular expressions. The first thing must be before you can begin parsing a string is to determine exactly regular expression will be. There are two way follows:The first is to specify it by hand using normal syntax, and The second is to use the new RegExp() constructor Example: pattern = /:+/; pattern = new RegExp(":+"); The JavaScript replace() method allows a programmer to replace a found match with another string. that takes two arguments, one being the regular expression if you want to searched for, and the other being the replacement text you want substituted. Example: var c = "my first program JavaScript"; var i = c.replace(/javascript/, "JavaScript");

Das könnte Ihnen auch gefallen