48
LECTURE 8 21/11/11

Lecture 8

  • Upload
    slade

  • View
    38

  • Download
    0

Embed Size (px)

DESCRIPTION

Lecture 8. 21/11/11. Increment Operators. Decrement Operators. Example Increment Operators. Increment Operators var c;// declare c as a variable c=5;// let c equal to 5 document.writeln("Postincrementing"); - PowerPoint PPT Presentation

Citation preview

Page 1: Lecture  8

LECTURE 821/11/11

Page 2: Lecture  8

INCREMENT OPERATORSOperator Called Sample

ExpressionExplanation

++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides

++ postincrement a++ Use the current value of a in the expression in which a resides then increment a by 1

2

Page 3: Lecture  8

DECREMENT OPERATORSOperator Called Sample

ExpressionExplanation

-- predecrement --b Decrement b by 1, then use the new value of b in the expression where b resides

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

3

Page 4: Lecture  8

EXAMPLE INCREMENT OPERATORS<html><title>Increment Operators</title>

<head>

<script langauge="JavaScript">

var c; // declare c as a variablec=5; // let c equal to 5

document.writeln("<h3>Postincrementing</h3>");document.writeln(c); //prints the value of cdocument.writeln("<br>" + c++); /prints the value of c then incrementsdocument.writeln("<br>" + c); //prints the incremented value of c

4

Page 5: Lecture  8

CONTINUED….var c; // declare c as a variablec=10; // let c equal to 10

document.writeln("<h3>Preincrementing</h3>");document.writeln(c); //prints the value of cdocument.writeln("<br>" + ++c); // increments c by 1document.writeln("<br>" + c); //prints the incremented value of c

</script>

</head>

</html> 5

Page 6: Lecture  8

OUTPUT

6

Page 7: Lecture  8

Executes a statement or statements for a number of times – iteration.

Syntaxfor(initialize; test; increment){// statements to be executed}

Initial Value is the starting number of the loop.

If the condition(test) is true the code is executed.

The initial value is changed by the step size.7

FOR LOOPS

Page 8: Lecture  8

The expression is evaluated, if it is false, JavaScript moves to the next statement in the program

If it is true then the statement is executed and expression is evaluated again

Again if the expression is false the JavaScript moves on the next statement in script, otherwise it executes the statement that forms the body of the loop

8

FOR LOOPS

Page 9: Lecture  8

<html>

<head><title> For</title>

</head><body><script type="text/javascript">for (i = 0; i <= 5; i++){document.write("The number is " + i);document.write("<br />");}</script>

</body></html> 9

FOR LOOPS

Page 10: Lecture  8

While a condition is true execute one or more statements.

“While Loops” are especially useful when you do not know how many times you have to loop

but you know you should stop when you meet the condition, i.e. an indeterminate loop

10

WHILE LOOPS:

Page 11: Lecture  8

The while Loop is the basic statement that allows JavaScript to perform repetitive actions. It has the following syntax.

while (expression) {// Statement to be executed}… more code…

11

WHILE LOOP

Page 12: Lecture  8

This cycle continues until the expression evaluates to false

It is important that a Loop counter that is used within the body of the Loop is declared outside it.

12

WHILE LOOPS

Page 13: Lecture  8

HTML FORMS The opening and close of forms are in themselves

little use. Knowing the different form elements that can be

placed within these tags is central to effective form design. Text Field Password Field Hidden field Text Area Check box Radio button Drop-down menu Submit Button Reset Button Image Button 13

Page 14: Lecture  8

JAVASCRIPT FORM VALIDATION Using Different Methods and Built in

functions to validate data entered to the HTML form

14

Page 15: Lecture  8

FORM VALIDATION

Form validation is accomplished by using JavaScript to pre-process the information the user types into a form before the data is sent to a server application

This practice is much more efficient that allowing incorrectly formatted data to be sent to the server

15

Page 16: Lecture  8

FORM VALIDATION

If the Information is incorrectly formatted you can alert the user with a pop up and force them to correct the mistake

Form Validation is one of the more common uses of JavaScript.

How do we know if a form field is: Blank Not of proper data type Incorrectly filled out in any other way

16

Page 17: Lecture  8

BUILT IN JAVASCRIPT OBJECTS – STRINGS The reason that that String values and

String Objects can be used interchangeably is that JavaScript converts between these two types where necessary.

When you invoke a String object method on a string value (which is not an object and does not have methods) JavaScript coverts the value to a temporary String Object allowing the relevant method to be invoked. 17

Page 18: Lecture  8

WHAT ARE THE METHODS AND PROPERTIES?

String.charAt() Method String.subString()Method String.indexOf() Method String.lastindexOf() Method String.length Property String.toLowerCase() String.toUpperCase()

18

Page 19: Lecture  8

STRING METHOD DESCRIPTIONS AND EXAMPLES Length Property

The String.length property is a read only Integer that indicates the number of characters in the specified string

19

Page 20: Lecture  8

EXAMPLE

20

<html><body>

<script language="javascript">

var str="Ecommerce is great!“;document.write("<p>" + str + "</p>");document.write(str.length);

</script>

</body></html>

Page 21: Lecture  8

String.toLowerCase() Method. String.toLowerCase() Takes no arguments. Returns a copy of string with all uppercase

letters converted to lowercase. String.toUpperCase()

String.toUpperCase() Takes no arguments. Returns a copy of string with all lowercase letters

converted to uppercase.

21

String Method Descriptions and Examples

Page 22: Lecture  8

EXAMPLE

22

<html><body>

<script language="javascript">

var str=("HELLO World!");document.write(str.toLowerCase());

document.write("<br>");document.write(str.toUpperCase());</script>

</body></html>

Page 23: Lecture  8

STRING METHOD DESCRIPTIONS AND EXAMPLES

23

String.indexOf() Method string.indexOf(substring) string.indexOf(substring, start) Substring is the string that is

being searched for within string. Start is an optional argument. It

specifies the position within the string at which the search is to start.

The method returns the position of the first character of the first occurrence of the substring within a string that appears after the start position, if any or –1 if no such occurrence is found.

<html><head><title> IndexOf

Example</title>

<script language="javascript">

var myString="Ba Humbug!"var

pos=myString.indexOf("umb")

document.write(pos + "<br />");

</script></head><html>

Page 24: Lecture  8

24

<html><head><title> IndexOf Example</title><script language="javascript">

var greeting="How are you";var locate=greeting.indexOf("you",5);

if (locate>=0){

document.write("found at position: ");document.write(locate + "<br />");

}else{

document.write("Not found!");}

</script></head><html>

Page 25: Lecture  8

LASTINDEXOF METHOD String.lastIndexOf() Method

Same as String.indexOf() but searches a String backwards.

String.charAt(n) The index of the character to be returned

from the string. Returns the nth character of the string.

25

Page 26: Lecture  8

26

<html><head><title> IndexOf Example</title><script language="javascript">var str="Is great College?“;var pos=str.lastIndexOf("College");if (pos>=0)

{document.write("College found at position: ");document.write(pos + "<br />");

}else{

document.write("College not found!");}

</script></head><html>

Page 27: Lecture  8

EXAMPLE

27

<html><head><title> Char

At</title>

<script language="javascript">

var x="JavaScript is so exciting";

document.write(x.charAt(5));

</script></head><html>

Page 28: Lecture  8

SUBSTRING METHOD String.substring()

string.substring(from, to) From specifies the position within string of the

first character of the desired substring. From must be between 0 and string.length-1 To is an optional integer argument and can range

from anywhere 1 and string.length. This returns specified substring of the string

28

Page 29: Lecture  8

29

<html><body>

<script language="javascript">

var str="Ecommerce is great!";// 0123456789

document.write(str.substring(2,6));

document.write("<br /><br />");

document.write(str.substr(2,6));

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

Page 30: Lecture  8

CONVERTING STRINGS TO NUMBERS We know that strings that represent

numbers are automatically converted to actual numbers when used in a numeric context.

This can also be done explicitly. To allow flexible conversions we use

two built in functions: parseInt() parseFloat()

These functions convert and return any number at the beginning of a string, ignoring any trailing non-numbers. 30

Page 31: Lecture  8

CONVERTING STRINGS TO NUMBERS

31

parseInt() parses a string and returns an integer

<html><script type="text/javascript">

document.write(parseInt("40 years") + "<br />");document.write(parseInt("He was 40") + "<br

/>");document.write("<br />");document.write(parseInt("10")+ "<br />");

</script></html>

Page 32: Lecture  8

CONVERTING STRINGS TO NUMBERS

What happens when the data type conversion cannot be performed.

var anystring = “one”;var y = parseInt(anystring);

In this instance “NaN” is returned. NaN stands for Not A Number. How do we deal with this?

32

Page 33: Lecture  8

CONTINUED… isNaN() - This built in function will determine

whether or not a datatype is numeric. Checks for not-a-number. It will return true if argument passed is not a

legal number. It will return false if it is a legal number.

33

Page 34: Lecture  8

PARSEFLOAT()

The parseFloat() function parses a string and returns a floating point number.

This function determines if the first character in the specified string is a number.

34

Page 35: Lecture  8

35

<html>

<script type="text/javascript">

document.write(parseFloat("10.33") + "<br />");

document.write(parseInt("10.33") + "<br />");

document.write(parseFloat("40 years") + "<br />");

document.write(parseFloat("He was 40") + "<br />");

</script>

</html>

Page 36: Lecture  8

CONVERTING STRINGS TO NUMBERS We know that strings that represent

numbers are automatically converted to actual numbers when used in a numeric context.

This can also be done explicitly. To allow flexible conversions we use

two built in functions: parseInt() parseFloat()

These functions convert and return any number at the beginning of a string, ignoring any trailing non-numbers. 36

Page 37: Lecture  8

CONVERTING STRINGS TO NUMBERS

37

parseInt() parses a string and returns an integer

<html><script type="text/javascript">

document.write(parseInt("40 years") + "<br />");document.write(parseInt("He was 40") + "<br

/>");document.write("<br />");document.write(parseInt("10")+ "<br />");

</script></html>

Page 38: Lecture  8

CONVERTING STRINGS TO NUMBERS

What happens when the data type conversion cannot be performed.

var anystring = “one”;var y = parseInt(anystring);

In this instance “NaN” is returned. NaN stands for Not A Number. How do we deal with this?

38

Page 39: Lecture  8

CONTINUED… isNaN() - This built in function will determine

whether or not a datatype is numeric. Checks for not-a-number. It will return true if argument passed is not a

legal number. It will return false if it is a legal number.

39

Page 40: Lecture  8

PARSEFLOAT()

The parseFloat() function parses a string and returns a floating point number.

This function determines if the first character in the specified string is a number.

40

Page 41: Lecture  8

41

<html>

<script type="text/javascript">

document.write(parseFloat("10.33") + "<br />");

document.write(parseInt("10.33") + "<br />");

document.write(parseFloat("40 years") + "<br />");

document.write(parseFloat("He was 40") + "<br />");

</script>

</html>

Page 42: Lecture  8

FORM VALIDATION EXAMPLE<html><head><script language="javascript">var x;var firstname;var country1;var email;var phone1;var comment1;var at;var dot;

function validate1(){x=document.myForm;at=x.myEmail.value.indexOf("@");dot=x.myEmail.value.indexOf(".");firstname=x.myname.value;country1=x.country.value;email=x.myEmail.value;phone1=x.phone.value;comment1=x.comment.value;

Page 43: Lecture  8

if (firstname =="") { alert("You must complete the name field");

x.myname.focus();return false;}else if(isNaN(firstname)== false){alert("Please enter your name correctly");x.myname.focus();return false;}

else if (country1 =="") { alert("You must complete the country field");

x.country.focus();return false;}else if(isNaN(country1)== false){alert("Please enter country correctly");x.country.focus();return false;}else if(email == "")

{alert("Please enter a vaild e-mail address");x.myEmail.focus();return false; }

Page 44: Lecture  8

else if (at==-1) {alert("Please enter a vaild e-mail address ");x.myEmail.focus();return false; }else if (dot==-1) {alert("Please enter a vaild e-mail address ");x.myEmail.focus();return false; }else if(phone1==""){alert("Please enter your phone number");x.phone.focus();return false;}else if(isNaN(phone1)==true){alert("That phone number is not valid");x.phone.focus();return false;}else if(comment1==""){alert("Please enter your comment!");x.comment.focus();return false;}return true;} </script>

Page 45: Lecture  8

</head><body><form name="myForm" action="submitform.html" onSubmit="return validate1();">

Enter your First Name: <input type="text" name="myname"> <br>

Enter your Country: <input type="text" name="country"> <br>

Enter your e-mail: <input type="text" name="myEmail"> <br>

Enter your Phone Number: <input type="text" name="phone"> <br>Your Comment: <input type="textarea" name="comment"> <br>

<input type="submit" value="Send input"> </form></body></html>

Page 46: Lecture  8

SAMPLE MCQ QUESTIONS1. A pixel is a _____ measurement of length

a) Absoluteb) Relativec) Indeterminated) Positioning

2. Checkboxes are not mutually exclusive form objects, this means

a) Only one option may be checkedb) They may use the checked keywordc) More than one option may be checkedd) None of the above 46

Page 47: Lecture  8

3. String methods ____ and ____ search for the first and last occurrence of a substring in a string respectively.

a) substr and substringb) indexOf and lastIndexOfc) charAt and indexOfd) None of the above

47

Page 48: Lecture  8

<html><head><title> IndexOf Example</title><script language="javascript">var greeting="How are you";var locate=greeting.indexOf("you",5);if (locate>=0)

{document.write("found at position: ");document.write(locate + "<br />");}else{document.write("Not found!");}

</script></head><html>

a)errorb)Not found!c)found at position: 8d)found at position:5