INT222 – Internet Fundamentals

41
INT222 – Internet Fundamentals Week 10: Math Object, Build-in Functions/Methods, JavaScript Validation 1

description

INT222 – Internet Fundamentals. Week 10: Math Object, Build-in Functions/Methods, JavaScript Validation. Outline. Math Object Build-in Functions/Methods JavaScript Validation Assignment #3 released. JavaScript Math Object. Math functions ( common method of the Math object). - PowerPoint PPT Presentation

Transcript of INT222 – Internet Fundamentals

Page 1: INT222 – Internet Fundamentals

1

INT222 – Internet Fundamentals

Week 10: Math Object, Build-in Functions/Methods, JavaScript

Validation

Page 2: INT222 – Internet Fundamentals

2

Outline

• Math Object• Build-in Functions/Methods• JavaScript Validation

• Assignment #3 released

Page 3: INT222 – Internet Fundamentals

3

JavaScript Math Object

Page 4: INT222 – Internet Fundamentals

4

Math functions (common method of the Math object)

• Math.max(ident_1, ident_2) – the maximum of n numbers– e.g. alert( Math.max(0.52, 1) ); // 1

• Math.min(ident_1,ident_2) – the minimum of n numbers– e.g. alert( Math.min(0.52, 1) ); // 0.52

• Math.pow(ident_1, ident2) – ident_1 to the power ident_2– e.g. alert( Math. pow(2, 8) ); // 256

• Math.sqrt(ident_1) – square root of– e.g. alert( Math. sqrt(9) ); // 3

Page 5: INT222 – Internet Fundamentals

5

Rounding floating-point

• Math.ceil(ident_1)– integer closest to and not less than– e.g. alert( Math.ceil(0.52) ); // 1 alert( Math.ceil(0.49) ); // 1

• Math.floor(ident_1) – integer closest to and not greater than– e.g. alert( Math.floor(0.52) ); // 0

• Math.round(ident_1) – integer closest to– e.g. alert( Math.round(0.52) ); // 1 alert( Math.round(0.49) ); // 0 alert( Math.round(0.5) ); // 1

Page 6: INT222 – Internet Fundamentals

6

Generating Random Number

• Math.random() - pseudorandom number– Return a floating point number between 0

(inclusive) and 1 (exclusive)– e.g. alert( Math.random() ); // 0.03517110995016992

• Generating number 1 to 10Math.floor((Math.random()*10)+1);

Page 7: INT222 – Internet Fundamentals

7

JavaScriptBuilt-in Functions/Methods

Page 8: INT222 – Internet Fundamentals

8

escape(myString) function

• Used to encode string, same as encodeURI() .• The function takes a non-alphanumeric string

as its argument and returns the ASCII value (in hexadecimal form) for each character in the string preceded by a % sign.

• If the string includes alphanumeric characters or -+*/_.@, those characters are returned unchanged.

• Blank characters are returned as %20

Page 9: INT222 – Internet Fundamentals

9

Examples

• alert( escape("qwertyuiopfghjklzxcvbnm") );// qwertyuiopfghjklzxcvbnm

• alert( escape("QWERTYFGHJKLZXCVBNM") );// QWERTYFGHJKLZXCVBNM

• alert( escape("1234567890-+*/_.@") );// 1234567890-+*/_.@

• alert( escape(" ~`!#$%^&()=\|\\[]{};':\",<>?") ); // %20%7E%60%21%23%24%25%5E%26%28%29%3D%7C%5C%5B%5D%7B%7D%3B%27%3A%22%2C%3C%3E%3F

Page 10: INT222 – Internet Fundamentals

10

eval(myString) function

• The eval() function uses one argument: a string. – If the string is an expression, eval()

evaluates/executes the expression.– If the string is made up of JavaScript statements,

eval() performs the statements.

Page 12: INT222 – Internet Fundamentals

12

isNaN(myString) function

• The isNaN() function is used to determine if an argument is "NaN" (not a number).

• example

alert( isNaN("123") ); // false

alert( isNaN(123) ); // false

alert( isNaN("123 456 789") ); // true

alert( isNaN("+123") ); // false

alert( isNaN("123+") ); // true

alert( isNaN(" 123 ") ); // false

Page 13: INT222 – Internet Fundamentals

13

parseFloat(myString) function

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

• If a character other than a numeral, a sign (+ or -), or an exponent is found, the function returns the value up to that point.

• If the first character in the string cannot be converted to a number, the function returns "NaN".

Page 14: INT222 – Internet Fundamentals

14

Example

alert( parseFloat("15.25") ); // 15.25alert( parseFloat("0.000345") ); // 0.000345alert( parseFloat("0.00159+E") ); // 0.00159alert( parseFloat(" 1234") ); // 1234alert( parseFloat("x 1234") ); // NaNalert( parseFloat("1 2 3 4") ); // 1alert( parseFloat("1234 x 123") ); // 1234

Page 15: INT222 – Internet Fundamentals

15

parseInt(myString) function

• The parseInt() function parses its first argument (a string), and then

• tries to return an integer of the specified radix (or base).

• If a number in the string is beyond the base, parseInt() ignores the rest of the characters and returns an integer value up to that point.

Page 16: INT222 – Internet Fundamentals

16

Examples

• base 10 (decimal) examplesparseInt('15', 10) returns 15parseInt('15') returns 15parseInt(15.99, 10) returns 15parseInt('15*3', 10) returns 15parseInt('Hello') returns NaN

• base 16 (hex) examplesparseInt('F', 16) returns 15parseInt('FXX123', 16) returns 15

Page 17: INT222 – Internet Fundamentals

17

Examples

• base 8 (octal) exampleparseInt('17', 8) returns 15parseInt('18', 8) returns 1

• base 2 (binary) exampleparseInt('1111', 2) returns 15parseInt('1211', 2) returns 1

Page 18: INT222 – Internet Fundamentals

18

Note the following problemsparseInt('015',10) with base 10 returns 15 parseInt('015',8) with base 8 returns 13 parseInt('015',16) with base 16 returns 21

parseInt('15') with no base returns 15 - treated as decimalparseInt('015') with no base returns 15 - treated as octal parseInt('0x15') with no base returns 21 - treated as hex

parseInt(' 15') with a blank returns 15

Page 19: INT222 – Internet Fundamentals

19

unescape(myString) function

• The unescape() function is the exact opposite of the escape() function. Its argument is a string of ASCII values (in hexadecimal form), each preceded by a % sign. The function returns the character string.

var myString1 = "%20%7E%60%21%23%24%25%5E%26%28%29%3D%7C%5C%5B%5D%7B%7D%3B%27%3A%22";

unescape(myString1) returns ~`!@#$%^&()=|\[]{};':"

Page 20: INT222 – Internet Fundamentals

20

Number() function

• The Number() function returns the actual number value - when possible

var1 = truevar2 = falsevar3 = Mon Mar 17 2014 00:04:29 GMT-0400 (Eastern Daylight Time)

Number(var1) = 1Number(var2) = 0Number(var3) = 1395029069226

var var1= new Boolean(true);var var2= new Boolean(false);var var3= new Date();

Page 21: INT222 – Internet Fundamentals

21

Examples

var4 = 999var5 = 999 888var6 = 999var7 = abcNumber(var4) = 999Number(var5) = NaNNumber(var6) = 999Number(var7) = NaN

var var4= new String("999");var var5= new String("999 888");var var6= "999";var var7= "abc";

Page 22: INT222 – Internet Fundamentals

Parsing String to Number Without using functions

22

var str1 = "1234";var num1 = str1 * 1;

alert(num1 + "\n" + typeof num1);

var str2 = "1234.5678";var num2 = +str2;

alert(num2 + "\n" + typeof num2);

Page 23: INT222 – Internet Fundamentals

23

toFixed() Method

• The toFixed() method formats a number to a specific number of digits to the right of the decimal.

amount.toFixed() is : 165amount.toFixed(6) is : 165.254560amount.toFixed(2) is : 165.25

var amount = 165.25456;

Page 24: INT222 – Internet Fundamentals

24

Popup window, getElementById and more

• A demo:

Page 25: INT222 – Internet Fundamentals

25

Popup window syntax

1. Generate a popup window – on the fly :

• Example:– HTML form button:

– JS: getStarted() function in javascriptCode.js

messageWindow=window.open('','window target name', 'window properties'); messageWindow.document.write(content); messageWindow.document.close();

<input type="button" name='example1' class='nice' value=' Popup and focus ' onclick="getStarted( );" />

Page 26: INT222 – Internet Fundamentals

26

Popup window syntax

2. Generate a popup window – Static : messageWindow=window.open('url','window target name', 'window properties'); messageWindow.document.close();

Page 27: INT222 – Internet Fundamentals

27

Get value of input field(type=text or similar)

• Include – Input type: text, number, password, date, email, …– textarea

• A values of input fields are strings, even if input type is number.

• Example: HTML form and fields<form method='post' action=‘#' name='formexample'> … … <input type="text" name="example2" id="example2" size='35' class='inputtext' /></form>

Page 28: INT222 – Internet Fundamentals

28

Get value of input field(type=text or similar)

Three basic ways:1. Check field value by Id

– HTML:<a href="" onclick="return checkText2();">Check By Id</a><br />

– JavaScriptcheckText2() function in javascriptCode.js

var textLength = document.getElementById("example2").value.length; var actualText = document.getElementById("example2").value;

Page 29: INT222 – Internet Fundamentals

29

Get value of input field(type=text or similar)

2. Check field value by Document reference

– HTML:<a href="" onclick="return checkText1();">Check Document reference</a>

– JavaScriptcheckText1() function in javascriptCode.js

var textLength = document.formexample.example2.value.length; var actualText = document.formexample.example2.value;

Page 30: INT222 – Internet Fundamentals

30

Get value of input field(type=text or similar)

3. Check field value by object location

– The index is based on • how many forms/elements in a page/form.• The sequence of the forms/elements in a page/form

– HTML:<a href="" onclick="return checkText3();">Check By Ojbect Location</a>

– JavaScriptcheckText3() function in javascriptCode.js

var textLength = document.forms[0].elements[2].value.length; var actualText = document.forms[0].elements[2].value;

Page 31: INT222 – Internet Fundamentals

31

Common sense logic

• Checkbox fields <input type='checkbox' name='example4' value='1'

onclick='commonSense();' />Option 1<br /> <input type='checkbox' name='example4' value='2'

onclick='commonSense();' />Option 2<br /> <input type='checkbox' name='example4' value='3'

onclick='commonSense();' />Option 3<br /> <input type='checkbox' name='example4' value='4'

onclick='commonSense();' />Option 4<br /> <input type='checkbox' name='example4' value='any'

onclick='uncheckTheAbove();' />Any of the above

Page 32: INT222 – Internet Fundamentals

32

Common sense logic• JavaScript Code

function commonSense() { document.formexample.example4[document. formexample.example4.length - 1].checked = false;}

function uncheckTheAbove() { var numberOfCheckboxes2 = document.formexample.example4.length - 1; for (var j = 0; j < numberOfCheckboxes2 ; j++) { document.formexample.example4[j].checked = false; }}

Page 33: INT222 – Internet Fundamentals

33

JavaScript Validation

Page 34: INT222 – Internet Fundamentals

34

JS validation example of type="text"

• By name– document.formname.elementname

• By elementById– document.getElementById("elementid") method

• By elementByName– document.getElementsByName("elementname") method– returns a collection

• By form and element index– document.forms[index].elements[index]– Not recommended

• With this key word – Using this key word in form element

Page 35: INT222 – Internet Fundamentals

35

JavaScript validation - textarea example

function checkForm() { var textareaLength = document.example.comments.value.length; var messages="<p>No. of characters in textarea = <mark>" + textareaLength + "</mark></p>"; if (textareaLength==0) { messages+= "<p>You did not type any text in the textarea</p>"; showErrors(messages); return false; // return false - allow for changes - form not submitted } else { messages +="<p>You typed</p><p>" + document.example.comments.value + "</p>"; showErrors(messages); return false; // return true - form will be submitted } } // End of function… …

Page 36: INT222 – Internet Fundamentals

36

JS validation - type="checkbox" example• Checkbox logic– Get the number of the checkboxes using length– Loop to check which one was checked– To determine which one is checked - if any

document.example.system_type[i].checked == true; // checkeddocument.example.system_type[i].checked == false; // not checked

Page 37: INT222 – Internet Fundamentals

37

JS validation - type="radio" example

• radio logic – Get the number of the radio using length– Loop to check which one was checked– To determine which one is checked - if any

document.example.system_type[i].checked == true; // checkeddocument.example.system_type[i].checked == false; // not checked

Page 38: INT222 – Internet Fundamentals

38

JavaScript validation - select examples

• Select options logic – Get the selectedIndex:var x = document.example.whatToDo.selectedIndex;– If selectedIndex == -1 • None are selected

– If the selectedIndex is NOT -1• document.example.whatToDo.options[x].value; – for the value

• document.example.whatToDo.options[x].text; – for the text

Page 39: INT222 – Internet Fundamentals

39

Text vs Value

• For the <select> <option> elements – dropdown list

<select> <option value=“This is a value">This is the text</option> <option value=" This is a value " selected>

This is another text </option></select>

• Any other form fields/controls have text attribute?

Page 40: INT222 – Internet Fundamentals

40

JavaScript validation - select / options - with multiple selections

• Select options logic : **multiple="multiple" **– Get the number of the select options using length

document.example.whatToDo.options.length;– Loop to check which one was selected– To determine which one is selected

• if any - check :if (document.example.whatToDo[i].selected == true) // selected

– document.example.whatToDo[i].value– document.example.whatToDo[i].text

Page 41: INT222 – Internet Fundamentals

41

Thank You!