JavaScript Functions, Objects and Array
Defining a Function A definition starts with the word function. A name follows that must start with a letter or underscore, followed by any number of letters, digits, dollar symbols, or underscores. The parentheses are required. One or more parameters, separated by commas, are optional. Function names are case-sensitive
Defining a Function naming convention for functions is camelcase The opening curly brace ( { ) starts the statements and a matching curly brace ( } ) must close it. These statements may include one or more return statements.
The arguments array The arguments array is a member of every function. You can determine the number of variables passed to a function and what they are.
Returning a Value
What did you learn for previous slide?
Returning an Array
JavaScript Objects An objects can contain multiple values and even functions. You need to design a composite of data and code called a class. Each new object based on this class is called an instance (or occurrence) of that class. The data associated with an object is called its properties and the functions it uses are called methods.
Declaring a Class declare the class called User and it is constructor at the same time properties method
Declaring a Class The different from other functions we ve seen so far : It refers to an object named this. this refers to the instance being created. The same function can be called over and over with different arguments, and will create a new User each time with different values for the properties. A new function named showuser is created within the function. Its purpose is to tie showuser to the User class.
Declaring a Class Separately defining a class and method
Creating an Object To create an instance of the class User Or you can create an empty object and then populate it later
Accessing Objects To refer to its properties To access the showuser method
The prototype Keyword prototype keyword can save a lot of memory In the User class, every instance will contain the three properties and the method. Therefore, if you have 1,000 of these objects in memory, the method showuser will also be replicated 1,000 times. However, because the method is identical in every case, you can specify that new objects should refer to a single instance of the method instead of creating a copy of it.
The prototype Keyword instead of using the following in a class constructor you could replace it with this
The prototype Keyword Declaring a class using the prototype keyword for a method
The prototype Keyword you can add a prototype property or method at any time, and all objects (even those already created) will inherit it User เปป น คลาส Details เปป น object
Static methods and properties JavaScript also supports static properties and methods from the class s prototype
JavaScript Arrays Numeric Arrays : To create a new array หรร อ Assigning element values หรร อ
Creating, building, and printing an array
Assignment using the array keyword You can create an array with some initial elements by using the Array keyword, like this
Associative Arrays An associative array is one in which its elements are referenced by name rather than by numeric offset To create an associative array, define a block of elements within curly braces arrays = { key1 : value, key2 : value, key3 : value, }
Creating and displaying an associative array key for loop using the in keyword
Multidimensional Arrays To create a multidimensional array in JavaScript, just place arrays inside other arrays
Using Array Methods concat foreach (for non-ie browsers) foreach (a cross-browser solution) join push and pop reverse sort
concat concatenates two arrays, or a series of values within an array
foreach (for non-ie browsers)
foreach (a cross-browser solution) To ensure cross-browser compatibility, you should use a statement such as the following
join With the join method, you can convert all the values in an array to strings and then join them together into one large string, placing an optional separator between them.
push and pop
reverse reverses the order of all elements in an array
sort Vdo สาธธ ตการททางาน function(a,b) https://www.youtube.com/watch?v=6_ozgykxirc
Questions?
Form Handling and Form Validation
Building Forms To build a form, you must have at least the following elements: An opening <form> and closing </form> tag A submission type specifying either a Get or Post method One or more input fields The destination URL to which the form data is to be submitted
Input Types Text boxes Text areas Checkboxes Radio buttons Hidden fields Select Labels Submit button
Default Values
Input Types
Text area
Checkboxes If you include the checked attribute, the box is already checked when the browser is displayed. If the user doesn t check the box, no value will be submitted, but if he does, a value is "on". If you prefer to have your own value you could use value attribute.
Checkboxes What is the different between and
Radio buttons They are used when you want only a single value to be returned from a selection of two or more options. All the buttons in a group must use the same name and only a single value is returned
Hidden fields
select
Labels With Label you can surround a form element, making it selectable by clicking any visible part contained between the opening and closing <label> tags
Submit button You can change the text of the submit button to anything you like by using the value attribute You can also replace the standard text button with a graphic image
Form in HTML5
The autocomplete attribute With autocomplete enabled, previous user inputs are recalled and automatically entered into fields as suggestions You can turn autocomplete on for an entire form but disable it for specific fields like this:
The autofocus a ttribute The autofocus attribute gives immediate focus to an element when a page loads. Can applied to any <input>, <textarea>, or <button>
The placeholder Attribute This attribute lets you place a helpful hint into any blank input field to explain to users what they should enter
The required Attribute used to ensure that a field has been completed before a form is submitted
The required Attribute Firefox Chrome http://www.the-art-of-web.com/html/html5-checkbox-required/#example1
More about HTML5 http://www.w3schools.com/html/html5_intro.asp http://www.html-5-tutorial.com/form-element.php http://www.tutorialspoint.com/html5/ https://www.youtube.com/watch?v=kdyjn7qqeta http://www.w3.org/tr/html5/forms.html
Validating User Input Client side validating : JavaScript Server side validating : any server side langage such as php, java, vb, c#,...
Validating User Input with JavaScript JavaScript validation should be considered an assistance to your users than to your websites. Because you cannot trust any data submitted to your server. May be some users disable JavaScript, or use browsers that don t support it
Sample Signup form
HTML
Script
Script
Script
Script
How's it work?
How's it work?
How's it work?
The regular expression ^[\w ]+$ will fail if the input is empty as it requires at least one character (because we used + instead of *)
Working with different types of FORM elements Value of Text / Textarea / Password boxes using the syntax : form.fieldname.value to test numeric values var field1 = parseint(form.field1.value); var field2 = parsefloat(form.field2.value)
Working with different types of FORM elements Value of Select / Combo / Drop-down boxes var selectbox = form.fieldname; var selectedvalue = selectbox.options[selectbox.selectedindex].value var selectedtext = selectbox.options[selectbox.selectedindex].text where fieldname is the SELECT element, which has an array of options and a value selectedindex that tells you which option has been selected.
Working with different types of FORM elements Checkboxes using the syntax : form.checkboxfield.checked return a boolean value (true or false) indicating the checkbox is in a 'checked' state
Working with different types of FORM elements Radio
Working with different types of FORM elements Checkbox array
http://www.the-art-of-web.com/javascript/validate/
Regular Expressions The pattern-matching algorithms within a single expression. Every regular expression must be enclosed in slashes Within these slashes, certain characters have special meanings; they are called metacharacters asterisk ( * ), plus sign ( + ), dot (. ), parentheses ( ), square brackets [ ], hyphen ( - ), caret ( ^ )
Regular Expressions * match any number of the preceding characters (Zero or more) + requires at least one. match anything except a newline ( ) treat this as a group [ ] inside the brackets you put a list of things that can match - indicate a range inside the brackets ^ match any characters except the following
Regular Expressions * match any number of the preceding characters Zero or more space + requires at least one at least a space, not allow LeGuin
Regular Expressions. match anything except a newline Match anything that lies between < and > even if there s nothing. will match <>, <em>, <br>, and so on if you don t want to match the empty case, <>
Regular Expressions ( ) treat this as a group At least a group of,000 1,000 1,000,000 1,000,000,000 1,000,000,000,000...
Regular Expressions [ ] inside the brackets you put a list of things that can match : There must be only one of them Match gray or grey - indicate a range inside the brackets or Match a number between 0-9
Regular Expressions ^ match any characters except the following match instances of Yahoo that lack!
You turn Explain : Explain :
Using Regular Expressions in JavaScript You can use regular expressions mostly in two methods: test and replace. test just tells you whether its argument matches the regular expression : return true or false replace takes a second parameter : the string to replace the text that matches. The replace generates a new string as a return value.
return true return dogs are friendly. I like dogs.
Summary of Metacharacters
Some example regular expressions
General Modifiers /g enables global matching. When using a replace function, specify this modifier to replace all matches, rather than only the first one. /i makes the regular expression match case-insensitive. Thus, instead of /[a-za-z]/, you can use /[a-z]/i or /[A-Z]/i /m enables multiline mode, in which the caret ( ^ ) and dollar( $ ) match before and after any newlines in the subject string. Normally, in a multiline string, ^ matches only at the start of the string, and $ matches only at the end of the string.
Questions?