INT222 – Internet Fundamentals
description
Transcript of INT222 – Internet Fundamentals
1
INT222 – Internet Fundamentals
Week 10: Math Object, Build-in Functions/Methods, JavaScript
Validation
2
Outline
• Math Object• Build-in Functions/Methods• JavaScript Validation
• Assignment #3 released
3
JavaScript Math Object
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
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
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);
7
JavaScriptBuilt-in Functions/Methods
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
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
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.
11
Example
var x = 10;var y = 20;var a = eval("x*y") + "\n";var b = eval("2+2") + "\n";var c = eval("x+17") + "\n";
var res = a + b + c;alert(res);
Result: 200427
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
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".
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
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.
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
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
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
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 ~`!@#$%^&()=|\[]{};':"
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();
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";
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);
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;
24
Popup window, getElementById and more
• A demo:
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( );" />
26
Popup window syntax
2. Generate a popup window – Static : messageWindow=window.open('url','window target name', 'window properties'); messageWindow.document.close();
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>
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;
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;
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;
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
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; }}
33
JavaScript Validation
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
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… …
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
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
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
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?
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
41
Thank You!