JavaScript 2

www.w3schools.com

 

JavaScript Objects Introduction

JavaScript is an Object Oriented Programming (OOP) language.

An object is a collective data type that possesses data and methods to transform data.

Properties (aka attributes)

Properties are the values associated with an object.

Example : the length property of the String object is used to return the number of characters in a string:

<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)
</script>

The output of the code above will be:

12

Methods

Methods are the actions that can be performed on objects.

Example :  the toUpperCase() method of the String object is used to display text in uppercase letters:

<script type="text/javascript">
var str="Hello world!"
document.write(str.toUpperCase())
</script>

The output of the code above will be:

HELLO WORLD!

 

JavaScript String Object

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

See Also: http://www.quirksmode.org/js/strings.html

Examples

Style strings

 

<html>

<body>

 

<script type="text/javascript">

 

var txt="Hello World!"

 

document.write("<p>Big: " + txt.big() + "</p>")

document.write("<p>Small: " + txt.small() + "</p>")

 

document.write("<p>Bold: " + txt.bold() + "</p>")

document.write("<p>Italic: " + txt.italics() + "</p>")

 

document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>")

document.write("<p>Fixed: " + txt.fixed() + "</p>")

document.write("<p>Strike: " + txt.strike() + "</p>")

 

document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>")

document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>")

 

document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>")

document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>")

 

document.write("<p>Subscript: " + txt.sub() + "</p>")

document.write("<p>Superscript: " + txt.sup() + "</p>")

 

document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>")

</script>

 

</body>

</html>

 

 

The indexOf() method

How to use the indexOf() method to return the position of the first occurrence of a specified string value in a string.

<html>

<body>

<script type="text/javascript">

var str="Hello world!"

document.write(str.indexOf("Hello") + "<br />")

document.write(str.indexOf("World") + "<br />")

document.write(str.indexOf("world"))

</script>

</body>

</html>

 

 

The match() method
How to use the match() method to search for a specified string value within a string and return the string value if found

<html>

<body>

<script type="text/javascript">

var str="Hello world!"

document.write(str.match("world") + "<br />")

document.write(str.match("World") + "<br />")

document.write(str.match("worlld") + "<br />")

document.write(str.match("world!"))

</script>

</body>

</html>

 

 

Replace characters in a string - replace()
How to use the replace() method to replace some characters with some other characters in a string.

<html>

<body>

<script type="text/javascript">

var str="Visit Microsoft!"

document.write(str.replace(/Microsoft/,"W3Schools"))

</script>

</body>

</html>

 

String Object Methods

Method

Description

anchor()

Creates an HTML anchor

big()

Displays a string in a big font

blink()

Displays a blinking string

bold()

Displays a string in bold

charAt()

Returns the character at a specified position

charCodeAt()

Returns the Unicode of the character at a specified position

concat()

Joins two or more strings

fixed()

Displays a string as teletype text

fontcolor()

Displays a string in a specified color

fontsize()

Displays a string in a specified size

fromCharCode()

Takes the specified Unicode values and returns a string

indexOf()

Returns the position of the first occurrence of a specified string value in a string

italics()

Displays a string in italic

lastIndexOf()

Returns the position of the last occurrence of a specified string value, searching backwards from the specified position in a string

link()

Displays a string as a hyperlink

match()

Searches for a specified string value in a string

replace()

Replaces some characters with some other characters in a string

search()

Searches a string for a specified value

slice()

Extracts a part of a string and returns the extracted part in a new string

small()

Displays a string in a small font

split()

Splits a string into an array of strings

strike()

Displays a string with a strikethrough

sub()

Displays a string as subscript

substr()

Extracts a specified number of characters in a string, from a start index

substring()

Extracts the characters in a string between two specified indices

sup()

Displays a string as superscript

toLowerCase()

Displays a string in lowercase letters

toUpperCase()

Displays a string in uppercase letters

toSource()

Represents the source code of an object

valueOf()

Returns the primitive value of a String object

 

JavaScript Array Object

The Array object is used to store a set of values in a single variable name

Defining Arrays

The following code line defines an Array object called myArray:

var myArray=new Array()

 

Two ways of adding values to an array: (you can add as many values as you need to define as many variables you require).

1: add as many values as needed

var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

 

Could pass an integer argument to control the array's size:

var mycars=new Array(3)
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

 

2:

var mycars=new Array("Saab","Volvo","BMW")

Example:

<html>

<body>

<script type="text/javascript">

var mycars = new Array()

mycars[0] = "Saab"

mycars[1] = "Volvo"

mycars[2] = "BMW"

for (i=0;i<mycars.length;i++)

{

document.write(mycars[i] + "<br />")

}

</script>

</body>

</html>

 

 

Accessing Arrays

·        Refer to it by name and index number.

·        The index number starts at 0.

var mycars=new Array(3)
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
 
document.write(mycars[0])

will result in the following output:

Saab

 

Modify Values in Existing Arrays

To modify a value in an existing array, add a new value to the array with a specified index number:

mycars[0]="Opel"

Now, the following code line:

document.write(mycars[0])

will result in the following output:

Opel

 

Sorting

·        Syntax : sort(compareFunction)

Parameters

CompareFunction - Specifies a function that defines the sort order.

·        If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

·        For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

 

Sorting Text – Compare function omitted

<html>

<body>

<script type="text/javascript">

var arr = new Array(6)

arr[0] = "Jani"

arr[1] = "Hege"

arr[2] = "Stale"

arr[3] = "Kai Jim"

arr[4] = "Borge"

arr[5] = "Tove"

document.write(arr + "<br />")

document.write(arr.sort())

</script>

</body>

</html>

 

 

Sorting Numbers

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function.

 

If a and b are two elements being compared, then:

So, the compare function has the following form:

function compare(a, b) {
   if (a is less than b by some ordering criterion)
      return -1
   if (a is greater than b by the ordering criterion)
      return 1
   // a must be equal to b
   return 0
}

 

To compare numbers instead of strings, the compare function can simply subtract b from a:

function compareNumbers(a, b) {
   return a - b
}

 

Example

<html>

<body>

<script type="text/javascript">

function sortNumber(a, b)

{

return a - b

}

var arr = new Array(6)

arr[0] = "10"

arr[1] = "5"

arr[2] = "40"

arr[3] = "25"

arr[4] = "1000"

arr[5] = "1"

document.write(arr + "<br />")

document.write(arr.sort(sortNumber))

</script>

</body>

</html>

 

 

 

Converting Strings to Numbers:

parseFloat syntax:  parseFloat('string')

How it works:

·        The argument of parseFloat must be a string or a string expression.

·        The result of parseFloat is the number whose decimal representation was contained in that string (or the number found in the beginning of the string).

·        If the string argument cannot be parsed as a decimal number, the results will be different in different browsers (either 0 or NaN).

·        Examples (comments in each line give the conversion results):

parseFloat('1.45kg')  // 1.45

parseFloat('77.3')    // 77.3

parseFloat('077.3')   // 77.3

parseFloat('0x77.3')  // 0

parseFloat('.3')      // 0.3

parseFloat('0.1e6')   // 100000

 

parseInt syntax:  parseInt( 'string' [, base] )

How it works:

·        The first argument of parseInt must be a string or a string expression.

·        The result returned by parseInt is an integer whose representation was contained in that string (or the integer found in the beginning of the string).

·        The second argument (base), if present, specifies the base (radix) of the number whose string representation is contained in the string. The base argument can be any integer from 2 to 36.

·        If there is only one argument, the number base is detected according to the general JavaScript syntax for numbers.

·        Strings that begin with 0x or -0x are parsed as hexadecimals; strings that begin with 0 or -0 are parsed as octal numbers.

·        All other strings are parsed as decimal numbers.

·        If the string argument cannot be parsed as an integer, the results will be different in different browsers (either 0 or NaN).

·        Examples (comments in each line give the conversion results):

parseInt('123.45')  // 123

parseInt('77')      // 77

parseInt('077',10)  // 77

parseInt('77',8)    // 63  (= 7 + 7*8)

parseInt('077')     // 63  (= 7 + 7*8)

parseInt('77',16)   // 119 (= 7 + 7*16)

parseInt('0x77')    // 119 (= 7 + 7*16)

parseInt('099')     // 0 (9 is not an octal digit)

parseInt('99',8)    // 0 or NaN, depending on the platform

parseInt('0.1e6')   // 0

parseInt('ZZ',36)   // 1295 (= 35 + 35*36)

 

Array Object Methods

Method

Description

concat()

Joins two or more arrays and returns the result

join()

Puts all the elements of an array into a string. The elements are separated by a specified delimiter

pop()

Removes and returns the last element of an array

push()

Adds one or more elements to the end of an array and returns the new length

reverse()

Reverses the order of the elements in an array

shift()

Removes and returns the first element of an array

slice()

Returns selected elements from an existing array

sort()

Sorts the elements of an array

splice()

Removes and adds new elements to an array

toSource()

Represents the source code of an object

toString()

Converts an array to a string and returns the result

unshift()

Adds one or more elements to the beginning of an array and returns the new length

valueOf()

Returns the primitive value of an Array object

 

JavaScript Math Object

·         The Math object allows you to perform common mathematical tasks.

·         The Math object includes several mathematical values and functions.

Mathematical Values

JavaScript provides eight mathematical values (constants) that can be accessed from the Math object.

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

 

Mathematical Methods

Examples of functions (methods):

The following example uses the round() method of the Math object to round a number to the nearest integer:

document.write(Math.round(4.7))

The code above will result in the following output:

5

 

The following example uses the random() method of the Math object to return a random number between 0 and 1:

document.write(Math.random())

The code above can result in the following output:

0.03155624673486179

 

The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10:

document.write(Math.floor(Math.random()*11))

The code above can result in the following output:

0

 

 

Math Object Methods

Method

Description

abs(x)

Returns the absolute value of a number

acos(x)

Returns the arccosine of a number

asin(x)

Returns the arcsine of a number

atan(x)

Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians

atan2(y,x)

Returns the angle theta of an (x,y) point as a numeric value between -PI and PI radians

ceil(x)

Returns the value of a number rounded upwards to the nearest integer

cos(x)

Returns the cosine of a number

exp(x)

Returns the value of Ex

floor(x)

Returns the value of a number rounded downwards to the nearest integer

log(x)

Returns the natural logarithm (base E) of a number

max(x,y)

Returns the number with the highest value of x and y

min(x,y)

Returns the number with the lowest value of x and y

pow(x,y)

Returns the value of x to the power of y

random()

Returns a random number between 0 and 1

round(x)

Rounds a number to the nearest integer

sin(x)

Returns the sine of a number

sqrt(x)

Returns the square root of a number

tan(x)

Returns the tangent of an angle

toSource()

Represents the source code of an object

valueOf()

Returns the primitive value of a Math object

More JavaScript and Forms

Examples:

 

valid_simple.html

<html>

<head>

<script language="JavaScript">

 

function testResults (form) {

     TestVar = isNumberString (form.inputbox.value)

     if (TestVar == 1)

          alert ("Congratulations! You entered only numbers");

     else

          alert ("Boo! You entered a string with non-numbers characters");

}

function isNumberString (InString)  {

     if(InString.length==0) return (false);

     var RefString="1234567890";

     for (Count=0; Count < InString.length; Count++)  {

          TempChar= InString.substring (Count, Count+1);

          if (RefString.indexOf (TempChar, 0)==-1) 

              return (false);

     }

     return (true);

}

</script>

</head>

<body>

<form name="myform">

Enter a string with numbers only:

<input name="inputbox" value="" type="text">

<input name="button" value="Click" onclick="testResults(this.form)" type="button">

</form>

</body>

</html>

 

String Object Methods Used:

1.    The substring() method extracts the characters in a string between two specified indices.

Syntax - stringObject.substring(start,stop)

Parameters

                       Start --Required. Where to start the extraction.  Must be a numeric value

                       stop -- Optional. Where to stop the extraction.  Must be a numeric value

 

2.    The indexOf() method returns the position of the first occurrence of a specified string value in a string.

Syntax  - stringObject.indexOf(searchvalue,fromindex)

Parameter

                       Searchvalue  -- Required. Specifies a string value to search for

                       Fromindex  -- Optional. Specifies where to start the search

 

Note: The indexOf() method is case sensitive!

Note: This method returns -1 if the string value to search for never occurs.

 

Example: Forms Computation

Formstaxex.html

<html>

 

<HEAD>

 

<SCRIPT LANGUAGE="JavaScript">

 

function  doMath() {

var one = eval(document.myform.total.value)

var two = eval(document.myform.tax.value)

var prod = one  *   two

document.myform.amount.value=custRound(prod,2);

}

 

function custRound(x,places) {

return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)

}

 

</script>

 

</HEAD>

 

<BODY>

 

<CENTER>

<FORM NAME="myform">

<table border="1">

  <tr>

    <td>Enter Total Amount </td>

    <td>

      <input type="text" name="total">

    </td>

  </tr>

  <tr>

    <td> Municipality </td>

    <td>

      <select name="tax">

        <option value="1.08375" selected> New York City </option>

        <option value="1.07375"> Westchester County </option>

        <option value="1.08625" > Nassau County </option>

        <option value="1.07875"> White Plains </option>

      </select>

    </td>

  </tr>

  <tr>

    <td>Total Including Tax</td>

    <td>

      <input type="text" name="amount">

    </td>

  </tr>

  <tr>

    <td> </td>

    <td>

      <input type="button" value="Calculate" onClick="doMath()" name="button">

    </td>

  </tr>

</table>

</FORM>

</CENTER>

 

</body>

</html>

 

·        Javascript eval function can execute JavaScript statements.

·        The eval function takes an argument as a string- this string can be a line of code, or a variable, or any piece of Javascript that could execute in the given context.

·        Here is an example:

var myvar1=0
var myvar2=0
var myvar3=0
/* set all variables to 100 */
for (i=1;i<4;i++) {
          eval("myvar" + i + "=100");
                  }

 

Example : JavaScript Calculator

 

calculator.html

<html>

<head>

<SCRIPT language=JavaScript>

    

     var CurOp="+";

     var CurTot=0;

     var CurNum=""

    

     function CalcNum(NewNum) {

     CurNum += NewNum;

     document.calcform.displaytext.value=CurNum;

     if (CurOp=="") {

     CurTot=0;

     CurOp="+";

     }

     }

     function ChangeOp(NewOp) {

     if (CurOp != "") {

     CurTot=eval(CurTot + CurOp + parseFloat(CurNum));

     CurNum="";

     document.calcform.displaytext.value=CurTot;

     }

     CurOp=NewOp;

     }

     function ChngSign() {

     if (CurNum != "") {

     CurNum = (parseFloat(CurNum) * -1).toString();

     }

     else {

     CurNum = "-";

     }

     document.calcform.displaytext.value=CurNum;

     }

     function CalcTot() {

     if (CurOp != "") {

     CurTot=eval(CurTot + CurOp + parseFloat(CurNum));

     CurNum="";

     CurOp="";

     document.calcform.displaytext.value=CurTot;

     }

     }

     function CalcClear() {

     CurOp="";

     CurNum="";

     CurTot="";

     document.calcform.displaytext.value="0";

     }

    

</SCRIPT>

 

</HEAD>

<CENTER>

<FORM name=calcform>

<TABLE class=CalcTable border=1>

  <TBODY>

  <TR>

    <TD colSpan=5><INPUT style="WIDTH: 100%; TEXT-ALIGN: right" readOnly

      value=0 name=displaytext></TD></TR>

  <TR>

    <TD><INPUT style="WIDTH: 25px" accessKey=7 onclick="CalcNum('7')" type=button value=7 name=but7></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=8 onclick="CalcNum('8')" type=button value=8 name=but8></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=9 onclick="CalcNum('9')" type=button value=9 name=but9></TD>

    <TD colSpan=2><INPUT style="WIDTH: 57px" accessKey=c onclick=CalcClear() type=button value=AC name=butAC></TD></TR>

  <TR>

    <TD><INPUT style="WIDTH: 25px" accessKey=4 onclick="CalcNum('4')" type=button value=4 name=but4></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=5 onclick="CalcNum('5')" type=button value=5 name=but5></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=6 onclick="CalcNum('6')" type=button value=6 name=but6></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=x onclick="ChangeOp('*')" type=button value=× name=butx></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=/ onclick="ChangeOp('/')" type=button value=÷ name=but/></TD></TR>

  <TR>

    <TD><INPUT style="WIDTH: 25px" accessKey=1 onclick="CalcNum('1')" type=button value=1 name=but1></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=2 onclick="CalcNum('2')" type=button value=2 name=but2></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=3 onclick="CalcNum('3')" type=button value=3 name=but3></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=+ onclick="ChangeOp('+')" type=button value=+ name=but+></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=- onclick="ChangeOp('-')" type=button value=- name=but-></TD></TR>

  <TR>

    <TD><INPUT style="WIDTH: 25px" accessKey=0 onclick="CalcNum('0')" type=button value=0 name=but0></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=. onclick="CalcNum('.')" type=button value=. name=but.></TD>

    <TD><INPUT style="WIDTH: 25px" accessKey=p onclick=ChngSign() type=button value=± name=but+-></TD>

    <TD colSpan=2><INPUT style="WIDTH: 57px" accessKey== onclick=CalcTot() type=button value== name=but=></TD></TR>

  </TBODY>

</TABLE>

</FORM>

</CENTER>

</html>

 

 

More Form Examples

http://www.codeave.com/javascript/category.asp?u_category=Forms

http://javascript.internet.com/forms/