1 / 57

BIT116: Scripting Lecture 16

Explore the basics of HTML forms, input elements, text fields, checkboxes, radio buttons, select lists, and more. Learn to create interactive forms to collect user data efficiently.

puga
Download Presentation

BIT116: Scripting Lecture 16

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. ASSIGNMENT ANNOUNCEMENTS Assignment 1GRADED AND RETURNED! Assignment 1 RevisionGRADED AND RETURNED! Assignment 2GRADED AND RETURNED! Woot! Woot! Assignment 2 Revisiondue Lecture 13, NEXTTuesday, August 18th, by midnight. Assignment 3due Lecture 14, NEXTThursday, August 20th, by midnight. Assignment 3 Revisondue on Lecture 16, Thursday, August 27th, by midnight.

  3. Basic Forms

  4. Basic Forms 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, submitbuttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements.

  5. Basic Forms • The <FORM> Tag • The <form> tag is used to create an HTML form: • <form>input elements go here…</form>

  6. Basic Forms The <INPUT> Element The most important form element is the <input> element. The <input> element is used to select user information. An <input> element can vary in many ways, depending on the type attribute. An <input> 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. Basic Forms • Text Fields • <input type="text"> defines a one-line input field into which a user can enter. • <form> • First name: <input type="text" name="firstname"><br> • Last name: <input type="text" name="lastname"> • </form> • 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. Basic Forms • The Password Field • <input type="password"> defines a password field. • <form> • Password: <input type="password" name="pw"> • </form> • 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. Basic Forms • Checkboxes • <input type="checkbox"> defines a checkbox. • Checkboxes allow a user select zero (0) or more options of a limited number of choices. • <form> • <input type="checkbox" name="vehicle" value="Bike">I have a bike<br> • <input type="checkbox" name="vehicle" value="Car">I have a car • </form> • How the HTML code above looks in a browser:

  10. Basic Forms • Radio Buttons • <input type="radio"> defines a radio button. • Radio buttons let a user select only one option of a limited number of choices: • <form> • <input type="radio" name="sex" value="male">Male<br> • <input type="radio" name="sex" value="female">Female • </form> • How the HTML code above looks in a browser:

  11. Basic Forms • Select Tag • <select> creates a drop-down list with multiple options. • <form> • <select> • <option value="bourbon">One Bourbon</option> • <option value="scotch">One Scotch</option> • <option value="beer">One Beer</option> • </select> • </form> • How the HTML code above looks in a browser:

  12. Basic Forms • OptGroup Tag • <optgroup> groups related options in a drop-down list. • <select> • <optgroup label="Fine Bourbons"> • <option value="ridgemont">1792 Ridgemont Reserve</option> • <option value="blantons">Blanton's Original Single Barrel</option> • </optgroup> • <optgroup label="Fine Scotches"> • <option value="laphroaig">Laphroaig Islay Single Malt</option> • <option value="master">Master of Malt 30 Year</option> • </optgroup> • </select>

  13. Basic Forms • Button • <button type="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: • <button type="button" onclick="alert('SURPRISE!')"> • Click Me for a Surprise!</button> • How the HTML code above looks in a browser:

  14. Basic Forms • Textarea • The <textarea> 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. • <form> • <textarea rows="4" cols="50"> • </textarea> • </form> • How the HTML code above looks in a browser:

  15. Basic Forms • Fieldset Tag • <fieldset> groups related elements in a form, allows for an (optional) legend, and draws a box around the group. • <form> • <fieldset> • <legend>Your Groovy Info</legend> • Groovy Name <input type="text"><br> • Groovy Email <input type="text"> • </fieldset> • </form> • How the HTML code above looks in a browser:

  16. Basic Forms • Submit Button • <input type="submit"> 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: • <form name="input" action="html_form_action.asp" method="get"> • … other form elements are here … • <input type="submit" value="Submit"> • </form> • How the HTML code above looks in a browser: See Form1 Example: http://faculty.cascadia.edu/cduckett/bit116/Lecture_06/form1.html

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

  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/data1.js http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data2.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/data2.js

  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: "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.

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

  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. Ultra Basic Example: Prompt() and Alert() with Data Types parseFloat() Example var a = parseFloat("10") + "<br>"; var b = parseFloat("10.00") + "<br>"; var c = parseFloat("10.33") + "<br>"; var d = parseFloat("34 45 66") + "<br>"; var e = parseFloat(" 60 ") + "<br>"; var f = parseFloat("40 years") + "<br>"; var g = parseFloat("He was 40") + "<br>"; var n = a + b + c + d + e + f + g; The result of n would be: 10 10 10.33 34 60 40 NaN

  27. Ultra Basic Example: Prompt() and Alert() with Data Types NaN The NaNproperty 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. Ultra Basic Example: Prompt() and Alert() with Data Types isNaN() The isNaN() function is Boolean and checks whether a number is an illegalnumber. This function returns trueif the value isNaN (Not a Number), and false if not (i.e., it is a legal number). Example var a = isNaN(123) + "<br>"; var b = isNaN(-1.23) + "<br>"; var c = isNaN(5-2) + "<br>"; var d = isNaN(0) + "<br>"; var e = isNaN("Hello") + "<br>"; var f = isNaN("2005/12/12") + "<br>"; var res = a + b + c + d + e + f;

  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").

  30. Ultra Basic Example: Prompt() and Alert() with Data Types Number() Example Convert different object values to their numbers: vartest1 = 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) + "<br>" + Number(test2) + "<br>" + Number(test3) + "<br>" + Number(test4) + "<br>" + Number(test5); The result of n would be: 1 0 1382704503079 999 NaN

  31. Ultra Basic Form Validation with JavaScript

  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. 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/validate3.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/validate3.js http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/echo1.zip

  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. Ultra Basic Form Validation with JavaScript jQuery Val() Method Examples Return the Value: <script> $(document).ready(function(){ $("button").click(function(){ alert($("input:text").val()); }); }); <body> Firstname: <input type="text" name="fname" value="Rex"><br> Lastname: <input type="text" name="lname" value="Winkus"><br><br> <button>Return the value of the first input field</button>

  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"); }); }); . . . <body> <p>Name: <input type="text" name="user"></p> <button>Set the value of the input field</button>

  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 iscase sensitive.

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

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

  40. Changing HTML on a Page with JavaScript

  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 <p> elements: • $("button").click(function(){  $("p").html("Hello <b>world</b>!");}); • Tip: To set or return only the text content of the selected elements, use the text() method. TIP

  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 <p> elements: • $("button").click(function(){  $("p").text("Hello world!");}); • Tip: To set or return the innerHTML (text andHTML markup) of the selected elements, use the html() method. TIP

  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 <p> elements • $("button").click(function(){  $("p").append("<b>Appended text</b>");}); • Tip: To insert content at the beginning of the selected elements, use the prepend() method. TIP http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/changing1.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_16/changing1.js

  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 <p> elements • $("button").click(function(){ • $("p").prepend("<b>Prepended text</b>"); • }); • Tip: To insert content at the end of the selected elements, use the append() method. TIP

  45. Numbers, Strings, and Dates

  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 resultwould be: • var x = 10; var y = 20; var a = eval("x * y"); 200var b = eval("1 + 2 + 3 + 4 + 5"); 15var c = eval("x + y + 17"); 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: • varnum = 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/zerosare added to create the desired decimal length. TIP

  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 • varstr = "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. Numbers, Strings, and Dates • JavaScript String toLowerCase() Method • The toLowerCase() method converts a string to lowercase letters. • Example: Convert the string to lowercase letters • varstr = "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. Numbers, Strings, and Dates • JavaScript String toUpperCase() Method • The toUpperCase() method converts a string to uppercaseletters. • Example: Convert the string to uppercase letters • varstr = "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 lowercaseletters. TIP

More Related