My Photos

My Photos
Rocking..

Wednesday 28 December 2011

Javascript Manual


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.
·          JavaScript is usually embedded directly into HTML pages
·           JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
·           Everyone can use JavaScript without purchasing a license
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
Javascript Rules
·         SCRIPT - The area between the <SCRIPT> and the </SCRIPT> tags defines the script program. Language - Defines the script language. Choices are JavaScript and VBScript.
·         SRC - Defines an external file containing the source code of the JavaScript. It may be a URL with the complete path to the script which may reside at another website. An example is:    <script language="JavaScript" SRC="testscript.js">
·         NOSCRIPT - The area between the <NOSCRIPT> and the </NOSCRIPT> tag is run by browsers that can't run JAVA script or have the feature turned off.
·         JavaScript code starts with the tag <script language="JavaScript"> and ends with the tag </script>. The code placed between <head> and </head>. Sometimes, people embed the code in the <body> tags
·         JavaScript statements end with semi-colons.
·         JavaScript is case sensitive.
·         JavaScript has two forms of comments:
·         Single-line comments begin with a double slash (//).
·         Multi-line comments begin with "/*" and end with "*/".
Document object
document.write("Hi there.")
·         In this code, document is the object. write is the method of this object.
Message Box
There are three message boxes: alert, confirm, and prompt.
Examples:
§  Alert(“Good Morning”);
§  window.confirm("Are you sure you want to quit?")
§  window.prompt("please enter user name")

* An alert can display whatever you want in the dialog box. The only differnce between alert and document.write is that the alert displays the message in a dialog box instead of on the web page and the alert function doesn't understand HTML so there is no point in including HTML tags into an alert call.
*  The confirm function differs from the alert function only in that it has two buttons to choose between instead of only one. The confirm function returns true or false depending on which of the two buttons is selected. If OK is selected then the confirm function returns true, if Cancel is selected it returns false.
*  The prompt() method displays a dialog box that prompts the visitor for input.This method returns the string the visitor has entered.
  Javascript Varibale
*  JavaScript variables are used to hold values or expressions. JavaScript variables can be declared with the var keyword
    Example: var x=5; var name=”Rama”.
Functions
* A function will be executed by an event or by a call to the function.
*  We may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file).
*  Javascript functions are defined using the key word "function" followed by its name and variables being passed
*  Function is two types: User defined function and Pre defined function.
Example1:  function without argument:
<script type=”text/javascript”>
            Function add(){
                        Var a=5;var b=7;
                        Var c=a+b;
                        Alert(c);
            }
            Add();
</script>
Example2:  Function with argument:
Function add(a,b){
                        Var c=a+b;
                        Alert(c);
          }
            Add(4,7);

Example3:  Function with argument with return type:
Function add(a,b){
            Var c=a+b;
            Return c;
          }
           Var c= Add(4,7);
Alert(c);
Event handler
*  Event handler can be considered as triggers that execute JavaScript when something happens, such as click or move your mouse over a link, submit a form etc.
* Events are normally used in combination with functions, and the function will not be executed before the event occurs!


Javascript Date Functions
·         The Date() is used to get today’s date and Time, The Date object is used to work with dates and times. 
Example:
var d=new Date();
document.write(d);
·         getFullYear() is uded to grt full Year
Example:
var d=new Date();
document.write(d.getFullYear());
·         getDay() is returned a weekday, and not just a number.
·         getHours()is returned Hour of the day (integer)(0-23)
·         getMinutes()is returned Minutes of the Last Hour (0-59)
Javascript Array
·         An array is a special variable, which can hold more than one value, at a time.
·         Values are stored into an array by using the array name
·         Values in an array are accessed by the array name and location of the value. Example: myCars [2];
Example : var myCars=new Array("Saab","Volvo","BMW");
·         Object we can access array by using array index.
Example: document.write(myCars[0]); // it will return the first value of myCars array.

·         concat() : Joins two or more arrays, and returns a copy of the joined arrays
Example:
<script type="text/javascript">

var fruit1= Array("apple","orange");
var fruit2= Array("Manago","banana");
var Fruit= fruit1.concat(fruit2);
document.write(Fruit);

</script>
·         pop():Removes the last element of an array, and returns that element.

Example:
<script type="text/javascript">

var fruit1= Array("apple","orange");
document.write(fruit1.pop());

</script>
·         push():Adds new elements to the end of an array, and returns the new length.
·         shift():Removes the first element of an array, and returns that element.
·         unshift():Adds new elements to the beginning of an array, and returns the new length
·         toString() : Converts an array to a string, and returns the result
·         reverse():Reverses the order of the elements in an array.
Javascript String
·         Strings are simply groups of characters. When we declare and manipulate strings in JavaScript, always write them with single quotes ' or double quotes " around them
·         toUpperCase():Convert any text or string from Lower case to Upper Case text by using this function.

var str="This is my 1st new tutorial 123";
var a1 = str.toUpperCase();
document.write(a1);

·         toLowerCase():convert Upper case text to Lower case text by using this function
·         length():Count the total number of chars present including the blank space by using length function.

var my_str="Hello world!"
document.write(my_str.length)

·         concat():add two or more strings by using concat function.
·         indexOf: This returns the first occurrence of a substring within the main string.

var my_str="Welcome to www.Google.com"
document.write(my_str.indexOf("Google "))

·         replace():replace function to search and replace part of a string.

var msg="Welcome to PHP tutorial section to learn PHP";
msg=msg.replace("PHP","JavaScript");
document.write(msg);


                Here is the code to search and replace all occurrence string.

<script type="text/javascript">
var msg="Welcome to PHP tutorial section to learn PHP";
msg=msg.replace(/PHP/g,"JavaScript");
document.write(msg);
</script>


·         split():Splits a string into an array of substrings
var str="2011-11-15";
alert (str.split("-"))

JavaScript Form Validation
JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Form data that typically are checked by a JavaScript could be:
  • has the user left required fields empty?
  • has the user entered a valid e-mail address?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?
Note: We can validate the form using two ways
·         With form (document.formname.fieldname.value)
·         Using ID(document.getElementById(‘id_name’).value);
Example:

HTML Code
<form name=”f1” action=”index.php” method=”post”>
Name:<input type=”text” name=”uname”/><br/>
Password:<input type=”password” name=”pass” id=”pass”/><br/>
<input type=”button” name=”Click” value=”click” onclick=”return validate();”/>
</form>
Javascript Code
<script type=”text/javascript”>
            Function validate(){
            Var name=document.f1.uname.value;  //Using form name and Field name we get value from text box
            Var pass=document.getElementById(‘pass’).value; //Using form name and Field name we get value from password field
            If(name==””){
                        Alert(“name cannot be blank”);
                        Return false;
            }
ld be six character length”);
                        Return false;
            }
If(pass==””){
                        Alert(“Password cannot be blank”);
Return false;
}
  }
If(pass.length<6 || pass.length>10){
                        Alert(“Password should be between six to tencharacter”);
                        Return false;
            }
</script>

No comments:

Post a Comment