Presentation is loading. Please wait.

Presentation is loading. Please wait.

Thursday, August 13 th, 2015 Instructor: Craig Duckett Basic Forms, Input/Output, Numbers, Strings, Dates.

Similar presentations


Presentation on theme: "Thursday, August 13 th, 2015 Instructor: Craig Duckett Basic Forms, Input/Output, Numbers, Strings, Dates."— Presentation transcript:

1 Thursday, August 13 th, 2015 Instructor: Craig Duckett cduckett@cascadia.edu Basic Forms, Input/Output, Numbers, Strings, Dates

2 2 ASSIGNMENT ANNOUNCEMENTS Assignment 1 GRADED AND RETURNED! Assignment 1 Revision GRADED AND RETURNED! Assignment 2 GRADED AND RETURNED! Woot! Woot! Assignment 2 Revision due Lecture 13, NEXT Tuesday, August 18 th, by midnight. Assignment 3 due Lecture 14, NEXT Thursday, August 20 th, by midnight. Assignment 3 Revison due on Lecture 16, Thursday, August 27 th, by midnight.

3 3 Basic Forms

4 4 HTML Forms HTML forms are used to pass data to a server. An HTML form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements.

5 5 Basic Forms The Tag The tag is used to create an HTML form: input elements go here…

6 6 Basic Forms The Element The most important form element is the element. The element is used to select user information. An element can vary in many ways, depending on the type attribute. An element can be of type text field, checkbox, password, radio button, submit button, and more. The most common input types are described in the next few slides.

7 7 Basic Forms Text Fields defines a one-line input field into which a user can enter. First name: Last name: How the HTML code above looks in a browser: Note: The form element itself is not visible. Also note that the default width of a text field is 20 characters. If you want to make it longer you can do so using the size element (e.g., size="30"). Note

8 8 Basic Forms The Password Field defines a password field. Password: How the HTML code above looks in a browser: Note: The characters in a password field are masked (shown as asterisks or dots). Note

9 9 Basic Forms Checkboxes defines a checkbox. Checkboxes allow a user select zero (0) or more options of a limited number of choices. I have a bike I have a car How the HTML code above looks in a browser:

10 10 Basic Forms Radio Buttons defines a radio button. Radio buttons let a user select only one option of a limited number of choices: Male Female How the HTML code above looks in a browser:

11 11 Basic Forms Select Tag creates a drop-down list with multiple options. One Bourbon One Scotch One Beer How the HTML code above looks in a browser:

12 12 Basic Forms OptGroup Tag groups related options in a drop-down list. 1792 Ridgemont Reserve Blanton's Original Single Barrel Laphroaig Islay Single Malt Master of Malt 30 Year

13 13 Basic Forms Button defines a clickable button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input: Click Me for a Surprise! How the HTML code above looks in a browser:

14 14 Basic Forms Textarea The tag defines a multi-line text input control. A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier). The size of a text area can be specified by the cols and rows attributes, or even better, through CSS' height and width properties. How the HTML code above looks in a browser:

15 15 Basic Forms Fieldset Tag groups related elements in a form, allows for an (optional) legend, and draws a box around the group. Your Groovy Info Groovy Name Groovy Email How the HTML code above looks in a browser:

16 16 Basic Forms Submit Button defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input: … other form elements are here … How the HTML code above looks in a browser: See Form1 Example: http://faculty.cascadia.edu/cduckett/bit116/Lecture_06/form1.htmlhttp://faculty.cascadia.edu/cduckett/bit116/Lecture_06/form1.html

17 17 REVIEW FROM LECTURE 6: Prompt() and Alert() Data Types

18 18 Ultra Basic Example: Prompt() and Alert() with Data Types Now that we've learned the basics of HTML form construction, we're going to backtrack for a bit and demonstrate how to use prompt() and alert() with some data types. Afterward we'll go on to see how JavaScript can interact with some basic HTML forms (we'll return to some more advanced forms at the end of the quarter) http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data1.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data2.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data1.js http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data2.js

19 19 Ultra Basic Example: Prompt() and Alert() with Data Types Strict Mode Starting with ECMAScript 5, developers are able to place their code into a more constrained form of execution known as strict mode. Strict mode improves JavaScript code by enforcing better programming practices and eliminating some of the language’s insecure and ill-advised features. Strict mode is enabled by adding the following directive to your code:ECMAScript 5 "use strict"; The “use strict”; directive can be used in two ways. The first method of invoking strict mode is at the file level. By adding the directive at the beginning of a file (the directive may only be preceded by comments and whitespace), strict mode is enabled in a global context. This means that all of your code will be evaluated in strict mode. Caution must be taken when concatenating strict and non-strict scripts together. Placing a strict script first will force the non-strict script to be evaluated in strict mode. Placing a non-strict script first will cause the opposite behavior. This caused some problems for Amazon.Amazon

20 20 Ultra Basic Example: Prompt() and Alert() with Data Types Strict Mode CONTINUED The second way to enable strict mode is at the function level. To enable this level of strict mode, place the “use strict”; directive at the beginning of the function body. As with global strict mode, the directive may only be preceded by whitespace and comments. Using strict mode at the function level allows a programmer to mix and match strict and non-strict functions in the same file. This is useful when some legacy code relies on features that have been deprecated in strict mode. The following example shows how strict and non-strict functions can coexist in a single file. function foo() { "use strict"; // this function is executed in strict mode } function bar() { // this function is executed in non-strict mode } One of the nice things about strict mode is its backward compatibility. Older versions of JavaScript will treat the “use strict”; directive as a meaningless string literal and ignore it. However, newer versions of JavaScript will give the statement special treatment and switch to strict mode.

21 21 Ultra Basic Example: Prompt() and Alert() with Data Types Strict Mode CONTINUED JavaScript has an interesting way of handling variable declarations. Variables that are not declared using the var keyword are implied to be global variables. The following piece of code uses three variables: x, y, and z. function foo() { var x; var z; x = 1; y = 2; z = x + y; } Notice that only the variables ‘x’ and ‘z’ are declared using the var keyword. There is a good chance that the programmer also meant to declare ‘y’, but mistakenly did not. The code will execute properly, but with the side effect of creating a global variable named ‘y’ with the value 2. Since window is the global object, this is equivalent to writing: window.y = 2;

22 22 Ultra Basic Example: Prompt() and Alert() with Data Types Strict Mode CONTINUED This behavior can be problematic if ‘y’ is already defined elsewhere and is expected to have a different value. This leads to code that doesn’t scale well and is difficult to debug. Enabling strict mode will catch this problem. Instead of making ‘y’ a global variable, an exception will occur. The exception shown in the browser might look like this: ReferenceError: y is not defined

23 23 Ultra Basic Example: Prompt() and Alert() with Data Types parseInt() Function The parseInt() function parses a string and returns an integer. The radix (or base) parameter is used to specify which numeral system to be used. For example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.radix If the radix parameter is omitted, JavaScript assumes the following: If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal) Note: Only the first number in the string is returned! Note: Leading and trailing spaces are allowed. Note: If the first character cannot be converted to a number, parseInt() returns NaN.

24 24 Ultra Basic Example: Prompt() and Alert() with Data Types parseInt() Example var a = parseInt("10") + " "; var b = parseInt("10.00") + " "; var c = parseInt("10.33") + " "; var d = parseInt("34 45 66") + " "; var e = parseInt(" 60 ") + " "; var f = parseInt("40 years") + " "; var g = parseInt("He was 40") + " "; var h = parseInt("10",10)+ " "; var i = parseInt("010")+ " "; var j = parseInt("10",8)+ " "; var k = parseInt("0x10")+ " "; var l = parseInt("10",16)+ " "; var n = a + b + c + d + e + f + g + " " + h + i + j + k +l; The result of n would be: 10 34 60 40 NaN 10 8 16

25 25 Ultra Basic Example: Prompt() and Alert() with Data Types parseFloat() Function 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. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string. Note: Only the first number in the string is returned! Note: Leading and trailing spaces are allowed. Note: If the first character cannot be converted to a number, parseFloat() returns NaN.

26 26 Ultra Basic Example: Prompt() and Alert() with Data Types parseFloat() Example var a = parseFloat("10") + " "; var b = parseFloat("10.00") + " "; var c = parseFloat("10.33") + " "; var d = parseFloat("34 45 66") + " "; var e = parseFloat(" 60 ") + " "; var f = parseFloat("40 years") + " "; var g = parseFloat("He was 40") + " "; var n = a + b + c + d + e + f + g; The result of n would be: 10 10.33 34 60 40 NaN

27 27 Ultra Basic Example: Prompt() and Alert() with Data Types NaN The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number. Tip: Use the isNaN() global function to check if a value is a NaN value. TIP

28 28 Ultra Basic Example: Prompt() and Alert() with Data Types isNaN() The isNaN() function is Boolean and checks whether a number is an illegal number. This function returns true if the value is NaN (Not a Number), and false if not (i.e., it is a legal number). Example var a = isNaN(123) + " "; var b = isNaN(-1.23) + " "; var c = isNaN(5-2) + " "; var d = isNaN(0) + " "; var e = isNaN("Hello") + " "; var f = isNaN("2005/12/12") + " "; var res = a + b + c + d + e + f;

29 29 Ultra Basic Example: Prompt() and Alert() with Data Types Number() Function The Number() function converts the object argument to a number that represents the object's value. If the value cannot be converted to a legal number, NaN is returned. Note: If the parameter is a Date object, the Number() function returns the number of milliseconds (a thousandth of a second) since midnight January 1, 1970 UTC ("Universal Time Coordinated").UTC

30 30 Ultra Basic Example: Prompt() and Alert() with Data Types Number() Example Convert different object values to their numbers: var test1 = new Boolean(true); var test2 = new Boolean(false); var test3 = new Date(); var test4 = new String("999"); var test5 = new String("999 888"); var n = Number(test1) + " " + Number(test2) + " " + Number(test3) + " " + Number(test4) + " " + Number(test5); The result of n would be: 1 0 1382704503079 999 NaN

31 31 Ultra Basic Form Validation with JavaScript

32 32 Ultra Basic Form Validation with JavaScript Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button. If some of the data that had been entered by the client had been in the wrong form or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process and over burdening server. JavaScript, provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions. Basic Validation - First of all, the form must be checked to make sure data was entered into each form field that required it. This would need just loop through each field in the form and check for data. Data Format Validation - Secondly, the data that is entered must be checked for correct form and value. This would need to put more logic to test correctness of data.

33 33 Ultra Basic Form Validation with JavaScript We'll continue to look at some ultra basic forms and form validation with JavaScript and jQuery: http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data3.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data3.js http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data4.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data4.js http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/validate1.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/validate1.js http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/validate2.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/validate2.js http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/echo1.zip http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/validate3.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/validate3.js

34 34 Ultra Basic Form Validation with JavaScript jQuery Val() Method The val() method has two (2) uses: it returns or sets the value attribute of the selected elements. When used to return value : SYNTAX: $(selector).val() This method returns the value of the value attribute of the FIRST matched element. When used to set value: SYNTAX: $(selector).val(value) This method sets the value of the value attribute for ALL matched elements. Note: The val() method is mostly used with HTML form elements.

35 35 Ultra Basic Form Validation with JavaScript jQuery Val() Method Examples Return the Value: $(document).ready(function(){ $("button").click(function(){ alert($("input:text").val()); }); Firstname: Lastname: Return the value of the first input field

36 36 Ultra Basic Form Validation with JavaScript jQuery Val() Method Examples Set the Value: $(document).ready(function(){ $("button").click(function(){ $("input:text").val("Rex Winkus"); });. Name: Set the value of the input field

37 37 Ultra Basic Form Validation with JavaScript indexOf() Method (JavaScript) The indexOf() method returns the position of the first occurrence of a specified value in a string. This method returns -1 if the value to search for never occurs. Note: The indexOf() method is case sensitive.

38 38 Ultra Basic Form Validation with JavaScript indexOf() Method Example (Returns a 15) Click button to locate where in string a specified value occurs. Try it function myFunction() { var str= "Rex Winkus for Supreme Leader!"; var n = str.indexOf("Supreme"); document.getElementById("demo").innerHTML = n; } Rex Winkus for Supreme Leader! 012345678901234567890123456789

39 39 Ultra Basic Form Validation with JavaScript indexOf() Method Example (Returns a -1) Click button to locate where in string a specified value occurs. Try it function myFunction() { var str= "Rex Winkus for Supreme Leader!"; var n = str.indexOf("supreme"); // <-- lower case document.getElementById("demo").innerHTML = n; }

40 40 Changing HTML on a Page with JavaScript

41 41 Changing HTML on a Page with JavaScript jQuery html() Method The html() method sets or returns the content (innerHTML) (text and HTML markup) of the selected elements. When this method is used to return content, it returns the content of the first matched element. When this method is used to set content, it overwrites the content of all matched elements. Example: Change the content of all elements: $("button").click(function(){ $("p").html("Hello world !"); }); Tip: To set or return only the text content of the selected elements, use the text() method. TIP

42 42 Changing HTML on a Page with JavaScript jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of all matched elements. Example: Set the text content for all elements: $("button").click(function(){ $("p").text("Hello world!"); }); Tip: To set or return the innerHTML (text and HTML markup) of the selected elements, use the html() method. TIP

43 43 Changing HTML on a Page with JavaScript jQuery append() Method The append() method inserts specified content at the end of the selected elements. Example: Insert content at the end of all elements $("button").click(function(){ $("p").append(" Appended text "); }); Tip: To insert content at the beginning of the selected elements, use the prepend() method. http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/changing1.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/changing1.js TIP

44 44 Changing HTML on a Page with JavaScript jQuery prepend() Method The prepend() method inserts specified content at the beginning of the selected elements. Example: Insert content at the beginning of all elements $("button").click(function(){ $("p").prepend(" Prepended text "); }); Tip: To insert content at the end of the selected elements, use the append() method. TIP

45 45 Numbers, Strings, and Dates

46 46 Numbers, Strings, and Dates JavaScript eval() Function The eval() function evaluates or executes an argument. If the argument is an expression even if it is a string, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements. Example: evaluate/execute expressions The result of result would be: var x = 10; var y = 20; var a = eval("x * y"); 200 var b = eval("1 + 2 + 3 + 4 + 5"); 15 var c = eval("x + y + 17"); 47

47 47 Numbers, Strings, and Dates JavaScript toFixed() Method The toFixed() method converts a number into a string, keeping a specified number of decimals. Example: Convert a number into a string, keeping only two decimals: var num = 3.14159265359; var n=num.toFixed(2); The result of n would be: 3.14 Note: if the desired number of decimals are higher than the actual number, nulls/zeros are added to create the desired decimal length. TIP

48 48 Numbers, Strings, and Dates JavaScript String substr() Method The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. Example: Extract parts of a string var str = "Hello world!"; var res = str.substr(4,4) The result of res would be: o wo Tip: To extract characters from the end of the string, use a negative start number (This does not work in IE8 and earlier) Note: The substr() method does not change the original string. TIP

49 49 Numbers, Strings, and Dates JavaScript String toLowerCase() Method The toLowerCase() method converts a string to lowercase letters. Example: Convert the string to lowercase letters var str = "Hello World!"; var res = str.toLowerCase(); The result of res would be: hello world! Note: The toLowerCase() method does not change the original string. Tip: Use the toUpperCase() method to convert a string to uppercase letters. TIP

50 50 Numbers, Strings, and Dates JavaScript String toUpperCase() Method The toUpperCase() method converts a string to uppercase letters. Example: Convert the string to uppercase letters var str = "Hello World!"; var res = str.toUpperCase() The result of res would be: HELLO WORLD! Note: The toUpperCase() method does not change the original string. Tip: Use the toLowerCase() method to convert a string to lowercase letters. TIP

51 51 Numbers, Strings, and Dates JavaScript toDateString() Method The toDateString() method converts the date (not the time) of a Date object into a readable string. Example: Convert today's date into a readable string var d = new Date(); var n = d.toDateString(); The result of n would be: Mon Jan 27 2014! Example: The Date() Object without the conversion: var d = new Date(); document.write(d); The result would be: Mon Jan 17 2014 15:05:33 GMT-0800 (Pacific Standard Time) TIP

52 52 Numbers, Strings, and Dates Some Methods of the Date Object: getMonth() The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time. Example: Return the Current Month var d = new Date(); var n = d.getMonth(); The result of n would be 0 January is 0, February is 1, March is 2, and so on. TIP

53 53 Numbers, Strings, and Dates Some Methods of the Date Object: getDate() The getDate() method returns the day of the month Example: Return the day of the month var d = new Date(); var n = d.getDate(); The result of n would be 27 The days of the month start with 1 instead of 0. TIP

54 54 Numbers, Strings, and Dates JavaScript toDateString() Method The toDateString() method converts the date (not the time) of a Date object into a readable string. Example: Convert today's date into a readable string var d = new Date(); var n = d.toDateString(); The result of res would be: Mon Jan 27 2014!

55 55 Assorted Libraries Custom Dialog Boxes Custom Dialog Boxes Date JS Date JS Pretty Date Pretty Date

56 56 Chapter 12: Math, Number, and Date Objects PLEASE NOTE : Due to the introductory discussion on Basic Forms, I did not cover much of the material that appears in Chapter 12 of the Pollock book, but you are still responsible for reading it! Some of the ICEs and Assignments will assume that you have read this chapter (as well as the other pertinent chapters in the book).

57 57 Please begin working on the LECTURE 12 In-Class Exercises. When you have completed your ICE, call the Instructor over to verify your work. If you have questions about your work, please call over the Instructor to clarify. Once you have completed your ICEs, you are free to go for the day. If you don't finish your ICEs by the end of class, you will still get full credit for actively doing the work, but it is greatly recommended you finish any outstanding ICEs outside of class.


Download ppt "Thursday, August 13 th, 2015 Instructor: Craig Duckett Basic Forms, Input/Output, Numbers, Strings, Dates."

Similar presentations


Ads by Google