Javascript Cyndi Hageman Javascript Basics n n Javascript

Javascript Cyndi Hageman

Javascript Basics n n Javascript is a scripting language, it is not compiled code. Javascript has object oriented capabilities. We create or manipulate objects that have properties and methods. Javascript is embedded in HTML code and is downloaded to the client’s machine when a web page is loaded. The code runs on the client machine, not the web server. Javascript will help make your web pages dynamic – you can interact with the client. Web pages alone are static and designed only for display.

Javascript Basics n n Case sensitive – an object named “txt. First. Name” is different than “txt. Firstname” and different from “txtfirstname”. There is no javascript function Alert() but there is a function alert(). Optional semi-colons – each javascript line of code can be ended with a semi-colon. It is not required but recommended.

Javascript Basics n n Comments – if you wish to add comments to your code you can add a one line comment by starting it with //. If you wish to comment out a block of code, start with /* and end with */. Literals – data values that appear in your program. n n 12 is the number 12 “Hello World” is a string of text true is the boolean value true null is the absence of value

Javascript Basics n n Identifier – simply a name. You will need to add a name to several things in javascript – a variable, a function, a loop, etc. Names can be anything you want with the exception of reserved words Reserved Words – words that have special meaning in javascript and cannot be used as identifiers. Words listed on page 19 & 20 in your book.

Simple Dialog Boxes n n alert() – alerts the client of something. It blocks the program from running until the user clicks OK. This is the most commonly used dialog box and is used a lot for debugging. prompt() – used to get a value from the client. The client types in a value and clicks OK and the value is returned to the program. This also blocks the program from running until the user clicks OK. Two parameters are passed to the prompt function. The first is the message to display. The second is a default value, which can be left blank.

Simple Dialog Boxes n n confirm() – tells the user something and they need to respond by clicking OK or Cancel. You can capture what they clicked and proceed accordingly. This blocks the program from running until the client responds. The alert() is used quite often. The confirm() and prompt() are not used as often and are not considered good design. There are better ways to get clients to enter information.

Examples of Dialog Boxes n n n alert(“You must enter your zip code. ”); var getanswer; getanswer=confirm(“Would you like to try again? ”); var val; val = prompt(“Please enter a number: ”, ””);

Variables n n A variable is a name associated with a value. The variable is said to store or contain a value. You declare the existence of a variable by using they keyword var i; var val; var i, val;

Variables and Data Types n n Javascript variables are untyped meaning they can hold any data type. What is a Data Type? n A data type is a type of value that can be represented or manipulated in javascript.

Primitive Data Types n n n Numbers – javascript recognizes integers, hexadecimal and octal literals, floating-point literals (decimals) Strings – sequence of characters contained between double quotes or single quotes. Booleans – data type that is a result of a comparison and can contain only 2 values – true or false.

Composite Data Types - Objects n An object an be an unordered collection of named values. These are often referred to as the properties of that object. n n ex: a web form is an object – the properties you set are name, method, action. You can read any of those properties like this: document. form 1. action ex: a web page itself is an object referred to as the document. There are properties you can read about that document, but there are methods you can perform on that object such as writing to it: document. write(“Hello World”);

Composite Data Types - Objects n An object can be an ordered collection of numbered values. These are called arrays. n n n An array is a collection of data values that are stored in the object and identified by an index. Array indexes start at 0. Declare a new array using the keyword Array: var arrvalues = new Array(); var arrvalues = new Array(10);

function n A function is a predefined block of code that can be executed when called. n A function can be defined by the programmer function check. Fields() n function setvalues(x, y) n n A function can be predefined by javascript: document. write(“Hello World”); n Math. round(x); n

Functions cont. n Functions accept arguments or parameters n Parameters are defined in the () of the function declaration function setvalues(x, y) accepts two arguments. When you call this function in your web page, you have to send it two arguments or you will get an error. n Function Math. round(x) requires one argument. This argument should be a number type so the math function can be performed. n

null and undefined n n null is a special value that indicates no value. If the value is returned as null, you know it does not contain a valid data type undefined is returned when a variable that has been declared has no value assigned to it or an object does not have a property defined for it.

is. Na. N n There is a special javascript function you can use to determine if a value is a number or not. n n n If is. Na. N(x) returns true, then the number passed is not a number. It is a string or a boolean. If is. Na. N(x) returns false, then the number passed to the function is a number. This will be used to determine if a value is a number that can be passed to the Math functions or if a value entered into a zip code field is a number, if not, make them enter it again.

Data Type Conversions n Numbers to Strings: n Use simple concatenation with a string n n var n= 5; var strn = n + “ is my favorite number. ”; Use the to. String method n var strn = n. to. String();

Data Type Conversion n Other methods for converting numbers to strings: var n=123456. 789 n n n. to. Fixed(0); //” 123457” n. to. Fixed(2); //” 123456. 79” n. to. Exponential(1); //” 1. 2 e+5” n. to. Exponential(3); //” 1. 235 e+5” n. to. Precision(7); //” 123456. 8”

Data Type Conversion n Strings to Numbers: n n When a string is used in a numerical context it is automatically converted to a number: var product = “ 22” + “ 15”; Explicitly convert by using the Number() function: var x=“ 22”; var number = Number(x);

Data Type Conversion n n parse. Int() can be used to retrieve an integer at the beginning of a string: parse. Int(“ 3 blind mice”) //returns 3 parse. Int(“ 12. 34”) // returns 12 parse. Float() can be used to retrieve integers and floating point numbers in a string: parse. Float(“ 3. 14”) //returns 3. 14 parse. Float(“ 12. 5 meters”) //returns 12. 5

Data Type Conversions n If parse. Int() or parse. Float() cannot convert a string to a number, it returns Na. N n n parse. Int(“eleven”) parse. Float(“$54. 45”) //returns Na. N

Data Type Conversion n Javascript will automatically convert boolean values: n n To numbers: true will convert to 1, false will convert to 0 To strings: true will convert to “true”, false will convert to “false” Any number other than 0 or Na. N is automatically converted to true, 0 or Na. N is converted to false Explicitly convert by using Boolean() function: var booleanvalue = Boolean(x);

Variable Scope n Region in a program in which a variable is defined n n Global variables – defined everywhere in your javascript code Local variables – defined within the function from which it was declared. Function parameters are considered local to that function.

Scope example <script language = “javascript”> var val; function getvalues(value 1, value 2) { var newvalue; } function setvalues(value 1, value 2) { newvalue = value 1; val = value 2; } </script>

Arithmetic Operators n Addition + n n n Subtraction – n n Attempt to subtract the second number from the first number Multiplication * n n Adds two numbers together Concatenates two strings together Attempts to multiply two numbers (also called operands) Division / n Attempts to divide the first number by the second

Arithmetic Operators n Modulo % n n Increment ++ n n Returns the remainder when the first operator is divided by the second a certain number of times Increments the operand by 1 or adds 1 Decrement -n Decrements the operand by 1 or subtracts 1

Order of Precedence n Arithmetic equations are read from left to right n n n If there is only addition and subtraction, they will be done in the order they appear If there is only multiplication and division they will be done in the order they appear. If there is a mixture of addition, subtraction, multiplication and division, the multiplication and division will be done first, then the addition and subtraction.

Examples var x = 20, y = 5, n = 10, m = 2; var val = x + n – y + m; //evaluates to 27 var val = n + x / y – n / m; //evaluates to 9 Add (), and anything in the () is done first var val = (n + x) / y – (n / m); //evaluates to 1

Examples var x = 20; var y = 5; var sum = x + y; var diff = x – y; var prod = x * y; var division = x / y; x = x++; y = y--;

if statement n Allows javascript to evaluate a statement and perform an action conditionally if (condition) { //perform javascript code within the curly brackets }

Equality Operators n Equality == n If first operand equals second operand, the condition evaluates to true. if (x == y) { //do code } if (x== y*4)

Identity Operator n Identity === n Compares two operands on strict definitions of sameness If both values are different data types, they are not identical n Same value or number they are identical n Same string with the characters in the exact same position n Both boolean values are true or both boolean values are false n

Inequality Operators n Not equal to != n n Checks of two values are not equal to each other Not identical to !== n Checks if two values are not identical to each other

Comparison Operators n Greater than > n n Less than < n n Checks if first operand is less than the second Greater than or equal to >= n n Checks if first operand is greater than the second Checks to see if the first operand is greater than or equal to the second Less than or equal to <= n Checks to see if the first operand is less than or equal to the second

if statement block n Can compare more than one condition in a single if statement n Need to determine the logical operator and && - used to determine if the first condition statement is true and the secondition statement is true then execute the code in the { } n or || - used to determine if any of the conditional statements evaluates to true, then the code in the {} will be executed. n


else n The else statement can be attached to the if statement to execute code if the condition in the if statement does not evaluate to true n if (condition) { //executes if condition is true } else { //executes if condition is false }

else if n Combines the else statement with another if evaluation n if (condition) { //executes if condition is true } else if (condition 2) { //executes if condition 2 is true } else { //executes if condition and condition 2 are false }

switch statement n Evaluates a condition and lists several possible answers. This can be used instead of a very long if/elseif statement. Use the break (or return) to get out of the statement when you find a match.

switch example var st = document. form 1. dlstates. value; var displayst = “”; switch (st) { case “IA”: displayst = “Iowa”; break; case “MN”: displayst = “Minnesota”; break; case “WI”: displayst = “Wisconsin”; break; }

while n Loop that will execute while a condition is true. The while loop evaluates the condition before the code is ever executed. The first time through, if the condition evaluates to false, the code will never be executed. n while (condition) { //executes while condition is true }

while example var cnt = 0; while (cnt <= 10) { //execute code as long as cnt is less than or equal to 10 cnt++; }

do while n This is very similar to the while loop only the condition is evaluated at the end of the loop so the code will always be executed at least once. n do { //executes the first time thru and will continue to execute as long as the while condition evaluates to true } while (condition)

do while example var cnt = 0; do { //will execute the first time thru cnt++; } while (cnt <= 10)

for loop n Loop that has a counter and tests the condition before the loop is ever executed. There are 3 things you must have in your for declaration: n n n The counter variable initialized The condition The counter variable updated for each loop

for loop example for (var i=0; i<=dlstate. length; i++) { if (document. form 1. dlstates. value == “IA”) { document. write(“Iowa”); break; } }

break n n This can be used to break out of a loop or a switch statement – once you have completed the task, there is no need to continue looping. Can be used with labels – labels are just identifiers you can use to associated with code, most often used with loops. You may want to use this with a nested loop.

break example Outerloop: for (var i=0; i<10; i++) { innerloop: for (var j=0; j<10; j++) { if (j>3) break; / if (i==2) break innerloop; if (i==4) break outerloop; } }

continue n n The continue is also used with loops. It indicates the loop should keep going with a new iteration (i++) while loop – expression at the beginning is tested again. do/while loop – skips to the bottom of the loop to check the expression for loop – the increment expression is evaluated
![continue example for (var x=0; x<data. length; x++) { if (data[x] == null) continue; continue example for (var x=0; x<data. length; x++) { if (data[x] == null) continue;](http://slidetodoc.com/presentation_image_h2/61e958fb5ccc79ac18a3222ec208a946/image-51.jpg)
continue example for (var x=0; x<data. length; x++) { if (data[x] == null) continue; total += data[x]; }

try/catch/finally n n try holds a block of code you want to execute catch hold the code you want executed if an exception occurs – an exception is basically an error finally is code that will be executed regardless of what happens in the try block – usually considered “clean up” code. If you use a try, you must have either a catch or a finally. You do not need both.

Arrays n n An array is an object that is an ordered collection of values. The values are stored in the array and are retrieved by referencing the array index. Arrays have one property – length. This is an integer telling how many elements are in the array.

Array Methods n n . join() – converts all the elements in the array to strings and concatenates them. You can pass in the character you want to separate them. If nothing is used, the list of values from the array will be comma delimited. . sort() – sorts the elements of the array and restores them in the same array – no copy of the array is made.
![Array’s cont. n Putting values into arrays arrvalue[0] = 1234; arrvalue[1] = “Hello World”; Array’s cont. n Putting values into arrays arrvalue[0] = 1234; arrvalue[1] = “Hello World”;](http://slidetodoc.com/presentation_image_h2/61e958fb5ccc79ac18a3222ec208a946/image-55.jpg)
Array’s cont. n Putting values into arrays arrvalue[0] = 1234; arrvalue[1] = “Hello World”; arrvalue[2] = 3. 14; var arrval = new Array(1234, “Hello World”, 3. 14); var arrval = [1234, “Hello World”, 3. 14];

Multi dimensional Arrays n n You cannot have a true multidimensional arrays, but you can store a new array with another array element. You can think of it as a table with rows and columns.

Multidimensional Array ex. var table = new Array(10); for (var i=0; i<table. length; i++) table[i] = new Array(10); for (var row=0; row<table. length; row++) for (var col=0; col<table[row]. length; col++) table[row][col] = row*column; var product = table[5][7];

functions n n A function is a block of javascript code that will be written once, but may be executed several times. Functions can be passed arguments or parameters which are local variables to that function. The value that is assigned to these functions are passed in when the function is called

function n You can name a function anything you want, as long as it is not a reserved word in Javascript. Make your names meaningful or descriptive. If a function has 2 parameters you must pass in two values when the function is called. There is an optional argument that can be used.

function set. Fields(value 1, /* optional */ value 2) { //this function takes two arguments, value 1 //is required, value 2 is optional }

return n Functions usually do something and in some cases they will return a value. The value could be a string, it could be a number, it could be a boolean. <form name=“form 1” Method=“POST” onsubmit=“return check. Fields(this)” action=“processform. asp”>

return function check. Fields(form) { //do all your checks to see if the data entered in //your form is valid. if (form. txt. First. Name. value == “”) { alert(“You must enter a first name); form. txt. First. Name. focus(); return false; } //if form data is valid, return true and the form is submitted. return true; }

Strings n n Property – length – returns the number of characters in a string Methods n n char. At() – extracts the character at a given position index. Of() – searches string for a character or substring and returns it’s numerical position. replace() – performs a search and replace operation split() – splits the string into an array of strings

strings n Methods cont. n n n substring() – extracts a substring of a string to. Upper. Case() – returns a copy of the string with all upper case letters. to. Lower. Case() – returns a copy of the string in all lower case letters.

String examples var strn = “Welcome to Javascript class”; strn. char. At(5) //returns m strn. index. Of(“J”) //returns 11 strn. length //returns 27 strn. replace(/class/i, “Class”) //class is Class var arrstrn = strn. split(“ “) //returns an array strn. substring(0, 7) //returns Welcome

String examples strn. to. Upper. Case() //returns “WELCOME TO JAVASCRIPT CLASS” strn. to. Lower. Case() //returns welcome to javascript class

Date() n n n Allows you to create a new date. May be used to retrieve current date and time. Remember, Javascript is running on the client machine. If you use the Date() functions, you are reading the date and/or time on the clients machine. Refer to page 613 for all the methods you can invoke on the Date() object.

Web Browsers n n Javascript is standardized and all modern browsers support it. Different platforms, Mac OS, Windows, Linux, however, may differ in their support of Javascript. http: //www. quirksmode. org/dom/ http: //webdevout. net/browser_support. php

Javascript Security n n n Javascript can open a window, but pop-up blocker may restrict it. Javascript can close a window, but usually, a confirmation is required. Javascript can not hide the destination of a link when you mouse over it. Javascript cannot open windows that are too small. Javascript cannot set the value of a file upload. Javascript cannot read the content of a document other than the document it resides on.

Window Object n n The window object is the global object for client side scripting. Some of these features may be hampered by modern security features.

Timer n n n Timer allows you to execute Javascript code in the future. set. Timeout() schedules a function to run after a specified number of milliseconds passes clear. Timeout() will cancel the scheduled execution. set. Interval() invokes a function at set intervals clear. Interval() clears the scheduled interval

location n n Location property references the location object or the current URL of the window You can read the URL of the page You can get the arguments that were passed as part of a query string You can load a new document into the window

history n n history. back() – takes the user back one page to the last visited document. history. forward() – takes the user forward one page in the list of visited documents. This is very similar to using the Back and Forward key on the browser window. Using these will allow you to provide your own navigation on a document.

Window size n Overall size of the browser window n n n window. outerwidth window. outerlength Position of the browser n n window. screenx window. screeny

Window size n Size of the view point in which the HTML document is displayed n n n window. inner. Width window. inner. Height Specify the horizontal and vertical scrollbars. They are used to specify between document and window coordinates. They specify the part of the document in the upper left hand corner n n window. page. XOffset window. page. YOffset

Navigator Object n Used to get information about the browser the client is using. n n n app. Name – name of the browser app. Version – displays the version number – may say 4. 0 to indicate compatibility with 4 th generation browsers user. Agent – displays information contained in both app. Name and app. Version app. Code. Name – code name of browser – IE and Netscape use Mozilla platform – hardware platform

window. open n Allows you to open a new window – it takes 4 optional arguments: n n URL of the document to be displayed Name of the window – serves as the target. If the window is already opened with that name, it loads the new document in it. Keeps the user from having several windows open at once. Features – can set the window size and GUI decorations Boolean value – used in conjunction with the second argument to determine whether or not URL in the first argument should replace the current windows URL in the browsing history.

window. open example var w = window. open(“newpage. html”, “newwindow”, ”width=400, height=350, status= yes, resizable=yes”, false);

Window. close n n window. close() – closes the current window. The user will be prompted with a confirm box if they actually want to close the window or not.

Setting focus n n window. focus() sets focus to that window and makes it the top level window on the stack window. blur() relinquishes the keyboards focus on that window.

W 3 C DOM n n Document Object Model Displays the document in a tree structure - see page 308 for example. Nodes – the node interface defines properties and methods for traversing through the tree. Different types of nodes – page 309

Finding Elements in a Document n get. Element. By. Tag. Name() gets the element by the tag name and all its elements n n get. Element. By. Tag. Name(“body”) will return an array of all the elements in the body of an HTML page get. Element. By. Id() – returns only the single element of the matching id. It does not return an array n get. Element. By. Id(“txt. First. Name”) will return this element and we can reference attribute of this element only

Cont. n get. Elements. By. Name() – returns an array of elements with that name n get. Elements. By. Name(“rdo. Conversion. Types”)[x]

inner. HTML Used to dynamically write or change the html text in an HTML document var table = document. create. Element(“table”); table. border = 1; table. inner. HTML = “<tr><th>Type</th><th>Value</th></tr>”; n

Attributes n set. Attribute() – sets an attribute of an element. document. form 1. set. Attrributes(“action”, “processform. asp”); n remove. Attribute() – removes an attribute of an element var spantag = document. get. Element. By. Id(“headerspan”); spantag. remove. Attribute(“align”); n get. Attribute() – retrieves the attribute of an element document. form 1. get. Attribute(“action”)

CSS and DHTML n You can change the style of an element by referencing the style property and setting the value n n n document. get. Element. By. Id(“spouseinfo”). style. display = “none”; document. get. Element. By. Id(“pagetitle”). style. color = “red”; See pages 347 -349 for properties and values

Positioning n n absolute – the position on the page is absolute and not part of the flow of the page. It is positioned in regard to the <body> or, if nested inside another positioned element, relative to that element. fixed – set the position in respect to the browser window. Fixed positioned elements are always visible and do not scroll with the document.

Positioning n relative – an element is laid out according to the normal flow of the document. When the position is relative, the position is adjusted based on where it’s normal position.

visibility vs. display n visibility determines whether an element if visible or not n n n document. get. Element. By. Id(“spouseinfo”). style. visibility = “visible” document. get. Element. By. Id(“spouseinfo”). style. visibility = “hidden” Using this style element will reserve the space on the layout of the page.

display n display will hide elements or display them without regard to the page layout. If an element is hidden, there is not space reserved for this element. n n document. get. Element. By. Id(“spouseinfo”). style. display = “none” document. get. Element. By. Id(“spouseinfo”). style. display = “” See page 348 for other values for display

External Stylesheets n You can link to an external stylesheet n n <link rel=“stylesheet” type=“text/css” href=“ss 0. css” id=“ss 0”> You can have alternate stylesheets that are disabled by default n <link rel=“alternate stylesheet” type=“text/css” href=“ss 1. css” id=“ss 1”>

External CSS function enable. SS(sheetid, enabled) { document. get. Element. By. Id(sheetid). disabled = false; } <input type=“checkbox” onclick=“enable. SS(‘ss 1’, this. checked)”>Bold

Events n n See page 390 and 391 for list of event handlers Set as an attribute: n n <input type = “button” name=“b 1” value = “Press Me” onclick=“send. User()”> Set as a property: n document. form 1. b 1. onclick = send. User();

DOM Level 2 n n Supported by all browsers except Internet Explorer Event Handler Registration n Use add. Event. Listener document. form 1. add. Event. Listener(“submit”, check. Fields(e. target), false) document. form 1. add. Event. Listener(“click”, showdiv, true)

Internet Explorer Event Model n n n Supported by IE 4 and above Not passed to an event-handler function, it becomes a property of the window object attach. Event n document. get. Element. By. Id(“b 1”). attach. Event( “onclick”, nameoffunction)

Forms n Form Object n n n You can use the submit() function in javascript to submit the form, very similar to the Submit button You can use the reset() function in javascript to reset the form, very similar to the Reset button. You can use the onsubmit property of a form to call a validation function and submit the form upon completion with a return of true.

Forms n You can refer to the form and it’s elements by name, or you can traverse through the form and all it’s elements as an array var form = new Object(); form = document. get. Element. By. Id(“form 1”), for (var x=0; x<form. length; x++) { alert(x + “ “ + form[x]. name) }

Forms n Form elements (page 440 & 441) n Name - every form element needs a name if the form is being submitted server side. It is best to give the form itself a name. <form name=“form 1”> document. form 1 document. forms[0] <form name = “address”> <input type = “text” name=“zip” value=“”> document. address. zip document. forms[1]. elements[4]

Forms n Properties n n Type – string telling the type of the form element form – reference to the form which contains it. name – string depicting the name you gave the element. value – a string that you can set as a default value when the form loads or set in your javascript with a value retrieved server side.

Forms n Event Handlers n n onclick – triggered when user clicks the element onchange – triggered when the user changes the value of a text field or selection box onfocus – triggered when the element receives input focus onblur – triggered when the element loses input focus

Push Button n Has no default value of it’s own and is pretty useless without an onclick event Works just like a link but gives the visual of a button Can use the <input> or <button> tag n n Using the <button> allows you to put text or an image as your button Properties are the same

Toggle buttons n Radio buttons or checkbox elements n n Can capture the onclick event. Some newer browsers also support the onchange event When the user clicks one of these elements, the state of that element changes from unchecked to checked. You can read the checked property to determine if it has been chosen if (document. form 1. rdo. MF[0]. checked == true)

Text boxes n Textbox, textarea, password and file elements Can use all the form events n Most commonly you read or set the value property var name = document. form 1. txtname. value; if ((name == “”) || (name == “ “)) { alert(“You must enter a name”); } n

Select and Option Elements n n Captures the onchange event The select tag does not contain the value property, each of the option tags do. If the user can only choose one option, you can use the selected. Index property to return the index or the value property to obtain the value of the selected option If the user can choose multiple options, you need to loop through the array of options and check the selected property of each option.

Select and Options Elements n n You can read the text of an option and change the value the user sees by access the text property of the options array document. form 1. dl. Month. options[2]. text = “March Madness”; You can make an option disappear by setting it to null document. form 1. dl. Month. options[2] = null;

Select and Option Elements n You can add an option to a select group n Use new Option constructor What the user sees n Value submitted to the form n Boolean to set the default. Selected property n Boolean to set the selected property n var vacation = new Option(“Vacation Month”, “vm”, false)

Examples //check if textbox has something in it var txtname = document. form 1. txtname. value; if ((txtname == “”) || (txtname == “ “)) { alert(“You must enter a name. ”); document. form 1. txtname. focus(); return false; }

Examples //checks to see if radio button is selected if ((document. form 1. rdo. MF[0]. checked == false) && (document. form 1. rdo. MF[1]. checked == false)) { alert(“You must choose Male or Female. ”); return false; }

Examples //check to see if user selected something in the drop down box if (document. dl. Month. selected. Index == 0) { alert(“You must select a valid month. ”); return false; }

Example //check to see if zip code entered is 5 digits var zip = document. form 1. zip. value; if (zip. length < 5) { alert(“You must entere a valid zip code”); document. form 1. zip. focus(); return false; }

Example //check to see if zip code entered is a number if (is. Na. N(document. form 1. zip. value)) { alert(“You must enter a valid numeric zip code”); document. form 1. zip. focus() return false; }

Cookies n n n A cookie is a small amount of data stored by the web browser and associated with a particular web page or web site. Cookies are written to the clients machine. Cookies are limited in size to 4 kb in size and the browsers only allow storage of 300 cookies total, 20 per web server. n Modern browsers allow more than 300 but if file size is greater than 4 kb, only 4 kb will be stored.

Cookie Attributes n n Cookies are stored with a name=value format. expires or max-age – the lifespan of a cookie only lasts as long as the browser is open. If you want it to last longer you must set the expire attribute to a certain date. In place of this you can use the max-age attribute which displays how long to keep the cookie alive in milliseconds.

Cookie Attributes n n n Path – which specifies the web with which the cookie is associated. You can set that path to allow any page with the path string in it to be viewed by that web site. Domain – this defaults to the host name but you can set this to a string to allow any page on with that domain on any server. You can only set the domain to a domain on your server. Secure – all cookies are secure and can be transmitted over an http connection. If it is secure, it must be a https connection
- Slides: 114