JavaScript CS 268 Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... What is JavaScript all about? Small program Runs in the client browser Typical uses: Perform simple calculations on existing Web page data Perform error checking on user inputs in HTML form elements Manipulate data that the developer embeds in the HTML document Create and read cookies Control the appearance of the current Web How a Script Works Scripts are interpreted Source code translated to machine language one line at a time each time script is run Actually it's more complicated than that – browsers today have hybrid JavaScript implementations that compile some of the code and where required interpret some of it. Can write with any text editor But – it's a "lot" easier if the editor provides color coding and code completion support! JavaScript and Object Oriented Programming JavaScript supports OO programming including inheritance It also supports try/catch error handling We aren't going to cover this But – with code to detect user entry errors this shouldn't be needed You can learn more about JavaScript OO from the following two links (not required for this class) http://www.javascriptkit.com/javatutors/oopjs.shtml http://www.crockford.com/javascript/inheritance.html Adding Javascript to a Web Page Add the script tag anywhere in the Web page body Place the tag where you want the script to execute Add the script commands within the script tags <script language="JavaScript" type="text/javascript"> first script command second script command … </script> Shortening the initial script tag to this is acceptable and recommended: <script> Browsers default to language="JavaScript" type=text/javascript if you omit these attributes http://www.javascriptkit.com/javatutors/languageattri.shtml Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... When does the script execute? If commands are not contained within a function, they execute in sequence as the page is loaded into the browser If contained within a function the commands do not execute until explicitly called by clicking a button (or other event) Where can you place a script? This is okay where it is normally placed if written in the html file (most other locations also work): <html> <head> <script> alert("Hello"); </script> <title>Hello Page Title</title> </head> Don’t do this (you can come up with other places it won't work): <html><head> <title>Hello Page Title <script> alert("Hello"); </script> </title> What will the alert display when this script runs? A – The alert will display Last name is: Smith B – The alert will display Last name is: C – The alert won't be displayed D – No idea… Affects of script location Can’t access a page object until it has loaded. For example this won’t work: <script> alert("The default employee last name is: " + document.frmEmployee.txtLastname.value); </script> <form name="frmEmployee"> <!-- initialize the last name to Smith --> <input name="txtLastname" value="Smith"> </form> But this will work: <form name="frmEmployee"> <!-- initialize the last name to Smith --> <input name="txtLastname" value="Smith"> </form> <script> alert("The default employee last name is: " + document.frmEmployee.txtLastname.value); </script> Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... JavaScript Data Types JavaScript is a loosely-typed language You don't declare the data type when you declare the variable The variable assumes the "correct" data type when you assign a value to it The language "usually" converts a variable value to the correct data type when you perform operations on it Data Types JavaScript types Boolean Number Object String Date (true, false) (10, -3.31) (document.frmForm1.txtInput) ("Now is the time") (12/4/2009) Data Types? The previous slide said it is "loosely typed" Data Types JavaScript variables assume the data type of whatever is assigned to them: var name = "Hello"; var whatever = 12; name is a string whatever is a number var whatever = "Something"; whatever is a string Using var to declare variables Don't have to use var But if you don't you can get some unexpected behavior – I'll show this in class Use var to get the usual (like Java) scoping of variables! Using var to declare variables Improved Try catch another possibility (but the upper solution is better): What happens now when the user assigns a name and then tries to display it? JavaScript Objects Variables (and constants) are also Objects Objects can do more than store a value Examples of object operations: String Number determine length of string convert to upper/lowercase letters convert to fixed number of places after the decimal point Date finding the current date/time from the system clock Example of String Object Properties & Methods Property or Method Description Example Result length Returns the length of a text string var myString = new String(); myString = "Joline"; var strLength = myString.length; 6 toLowerCase Converts a string to lowercase letters var myString = new String(); myString = "Joline"; var strLowerCase = myString.toLowerCase(); "joline" toUpperCase Converts a string to uppercase letters var myString = new String(); myString = "Joline"; var strUpperCase = myString.toUpperCase(); "JOLINE" Example of Number Object Properties & Methods Property or Method Description toFixed Rounds a number to a specified number of decimal places Example var myNumber = 3.14157; var myRoundedNumber = myNumber.toFixed(3); Result 3.142 Example of Date Object Properties & Methods Property or Method Description Example getFullYear() Returns the current four-digit year var myDate = new Date(); var CurrentYear = myDate.getFullYear(); getMonth() Returns the current month, as a number from 0-11 var myDate = new Date(); var CurrentMonth = myDate.getMonth(); getDate() Returns the current day of the month, from 1-31 var myDate = new Date(); var CurrentDate = myDate.getDate(); getHours(), getMinutes(), getSeconds() Returns the current hour (0-23), minute (059), or second (0-59) var myDate = new Date(); var CurrentHour = myDate.getHours(); Warning Declaring a variable using new won't prevent the variable from automatically converting to any data type assigned to it! Displaying the Current Date <html><head><title>Methods</title></head> Date objects have to <body> be created using new <script> var today = new Date(); var weekFromToday = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7); alert("Today's date is: " + today + "\n" + "A week from today is: " + weekFromToday); </script> </body></html> Tip: you can get code help for Date in Dreamweaver by entering Date( and looking at the help popuped up above it. If not shown try pressing ctrl-spacebar to display it Notice it has 4 constructors… Displaying the Current Date in short format Use today.getMonth today.getDate, and today.getFullYear Example - replace today in the previous slide's alert with: (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear() Add similar code using weekFromToday Why is today.getMonth() + 1 inside parentheses? Try removing them and see what happens. Why am I adding 1 to today.getMonth()? Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... Data Type Conversions All HTML form input values are text strings What if you need to change a value to a number? Motivations: Determine if an input number value is within a specific range Perform an addition operation on a form input JavaScript Conversion Functions Converting a string to a number parseInt(): converts a string to a number, and removes any fractional values parseFloat(): converts a string to a number, and includes any fractional values Examples: document.frmForm1.txtResult.value = parseInt(value1) + parseInt(value2); document.frmForm1.txtResult.value = parseFloat(value1) + parseFloat(value2); Code help for parseInt and parseFloat In Dreamweaver Code view within script element press Ctrl – Spacebar at the same time Type the letters you 'think' the command begins with (and/or scroll up and down to view options): Converting Numbers to Strings Concatenate number to an empty string Example: var myNumber = 13; myNumber = myNumber + ""; myNumber is now a String Concatenating Number Values and String Values + is an overloaded operator in JavaScript What if you combine strings and numbers in the same operation? used for both addition and concatenation add 2 numbers: result is a number add a string to a number: result is a string add a number to a string: result is a string If an operand on either side of the + is a string, the result is a string Given the following variable declarations, what is displayed by each JavaScript alert? var input1 = var input2 = var input3 = alert(input1 alert(input3 alert(input1 alert(input1 "15"; 10.4; 5; + input2 + input3); ______________________ + input2 + input1); ______________________ + (input2 + input3));______________________ * input3); ______________________ Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... HTML Forms Enhanced HTML documents that allow users to enter inputs onto Web pages using common interface controls Text inputs, radio buttons, command buttons, etc. When the user submits the Web page, the form passes the input values to the Web server Input values are called parameters Values are passed to the server in a parameter list Creating a Form form tag attributes: name: identifies the form internally within the Web page Example: name="customer" Form ID: newer syntax for identifying a form. If used, the name attribute and id should be the same Example: id="customer" name="customer" action: specifies the action the Web server performs with the form parameter list Usually involves calling a script or program that runs on the Web server (not in the user’s browser like JavaScript) method: how the Web server processes the parameters GET: passes the parameters as a list on the URL POST: sends the parameters directly to the receiving program Confusion between id and name attributes The id attribute (for example: id="one") can be added to any HTML element. <table id="data"> including form and input tags An element identified by a tag can be referenced in JavaScript using the document.getElementById method: document.getElementByID("data") This can allow modifying just about any aspect of a page's appearance using JavaScript In addition, if a style sheet is linked to the page, id's can apply id styles to an element Form tags and form element tags (input, select and textarea) allow using the name attribute. Names identify inputs to be sent to a Web server and can be used to access form input values using JavaScript. For example JavaScript accessing an input value might be: document.formName.inputName.value And a server jsp program reading the inputName value would use: request.getParameter("inputName"); The name attribute must be used for user form inputs with values that are to be sent to a web server If omitted, the value the users selects or enters for the input will NOT be sent to the server. Accessing form elements Array Notation: document.forms[index].elements[index].propertyOrMethodName Must know the index number (order in which the form and element appear in the page) Be warned that if you place any of the inputs in a different order or omit one and use array notation the array indexes will be off and the code will not work! Which is why I use names instead of array indexes. names (a good choice with javascript): document.formName.elementName.propertyOrMethodName or document.forms[index].elementName.propertyOrMethodName Names are easier to read and understand than array notation Except when validating radio inputs (more later) ids: document.getElementByID("fname").value Example Form Tag <form name="customer_order" method="post" action="ProcessOrder.jsp"> form input elements and text go here </form> Form Elements Most form elements are defined using the input tag <input type="input_type" name="input_name" value="input_value"> Type: text, button, radio, etc. Name: used to reference the element internally Value: the element’s initial or current value HTML Form Elements Description Function Type Sample Tag Text field Entering a single line of text text <input type="text" name="name"> Password field Entering a single line of text with values masked as "****" Password <input type="password" name="userpwd"> Command button Starting an action such as executing a script or program Button <input type="button" value="Whatever"> Submit command button Submitting a form to the Web server Submit <input type="submit" value="Login"> Reset command button Returning the form to its original state (clearing/resetting input values) Reset <input type="reset" value="Reset"> Radio button (or option button) Selecting a single value from a predefined group of item values Radio <input type="radio" name="pmtmethod"> Check box Specifying whether a value is true or false Checkbox <input type="checkbox" name="paid"> Lab1 introduces the HTML5 required attribute and type=email, number and date More HTML Form Elements Description Function Type Attribute Sample Tag Text area Entering multiple lines of text, such as a paragraph Not used <textarea name="comments"> Initially displayed text </textarea> Selection list Selecting a single item from a predefined list of items Not used <select name="colors"> <option value="1">Red</option> </select> Hidden element Storing a data item that is not visible to the user Hidden <input type="hidden" name="datemodified" value="stored data"> Text Fields Single line of text data Types Text Password All HTML form data is entered as text Characters, dates, numbers – they are all text Text Field Example <p>Please enter your name: <input name="UserName" type="text"> </p> Buttons Types Submit Reset Button Difference between Submit and Button? Submit automatically submits to the Web server Button requires the programmer to write JavaScript code to make something happen Button Examples <form name="username" action="nextPage.php"> Please enter your name: <input type="text" name="name"><br> <input type="submit" value="Submit Name"><br> <input type="reset" value="Clear Form"><br> <input type="button" value="Run Script" onclick="javaScriptFunction();"> </form> Radio Buttons Each individual button is part of a radio button group The name is the same for all buttons in the group It references the value of the currently-selected button The value and label attributes are different for each button Radio Button Code Example Check Boxes Indicates a data value that can have one of two values General syntax: The checked attribute makes the box checked at form startup <input type="checkbox" name="boxName" value="boxValue" checked> Check Box Example <p>Paid in Full <input name="paidStatus" type="checkbox" value="PAID" checked> </p> Selection Lists Defines a list from which the user can select one of a series of values Often used to display data retrieved from a database List value is the value of the selected list item Selection List Example <select name="products"> <option value="shorts">Shorts</option> <option value="tents">Tents</option> <option value="fleece">Women's Fleece</option> <option value="sandals">Children's Sandals</option> </select> Text Area Input field that can contain multiple lines of unformatted text You can specify the length and width Unlimited number of characters can be entered Sort of - this is browser dependent if you want to allow uploading entire books consider using the HTML input type="file" Text Area Example <textarea name="instructions" cols="40" rows="10"> Initial Text </textarea> Closing tag is required ( /> not allowed for the opening tag) Hidden Form Elements Useful for storing information that you don’t want the user to see Example: passing values from one form to another Syntax: <input type="hidden" name="userName" value="MORRISCM"> <form name="example" action="process.jsp" method="post"> <input type="text" name="quantity"> <input type="text" name="productID"> <input type="submit" value="Submit Order"> </form> When this form is submitted A) parameters are passed as a list on the URL B) parameters are passed directly to the web server C) What parameters? There are no parameters <select name="products"> <option value="shorts">Shorts</option> <option value="tents">Tents</option> <option value="fleece">Women's Fleece</option> <option value="sandals">Children's Sandals</option> </select> When this page is shown: A) This is displayed: B) This is displayed: When the above page is shown it is possible to select more than one at the same time. But – when using radio buttons only "one" should be selectable at a time. Why can more than one be selected? A) The value's should all have the same value (i.e., value=items for example) B) The name's should all be the same (i.e., name=items) C) The input type should be type=option for all of them D) None of them have a closing </input> tag Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... Browser Object Model (BOM) Hierarchy of objects providing programmatic access to the pages displayed in the browser Document Object Model (DOM) Not standardized among different browsers In practice most browsers have common implementations of browser objects Subset of the browser object model This IS standardized and compatible (mostly) across different browsers Many developers, books, articles, etc. refer to the DOM and don't refer to the BOM. Browser Object Hierarchy (basics) window document forms[] array images[] array history location navigator screen links[] array frames[] array elements[] array Document Object Model (DOM) HTML Document Object Hierarchy window document form text submit textarea reset password radio select option checkbox button Navigating the HTML Document Model Hierarchy to a form object is called its object path Reference a form object using dot syntax window.document.form_name.object_name Current window (always) Current HTML document (always) Enter the desired form name and object name (if a form is named, it is usually referenced by name rather than using forms[0] – same for elements contained within a form) window.document.forms[0].elements[0] Example: Form name: student Text field name: DOB You would reference the current value of DOB as: window.document.student.DOB.value NOTE: You can omit window when referencing a form object For example: document.student.DOB.value Some browsers also allow omitting document Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Cookies Creating a Custom Function Create the function declaration within script tags Defines the function: Function name Parameter list (optional) Commands that function executes Value that the function returns (optional) Create the function call(s) in the Web page body Calls the function Passes parameter values to it (if function has them) Creating a Custom Function Function definition Function calls in body Function Declaration Syntax function function_name (parameter1, parameter2, …){ function_commands return return_value; } Optional – only a parameter name is used – no type information Function Call Syntax function_name (parameter1, parameter2); function validateAge(age) { if(age == "") { alert("Please enter your age"); return false; } else if(isNaN(age) == true) { alert("Please enter a number for your age"); return false; } Whatever the user has entered return true; in the text input is sent to validateAge } as a parameter function validateUserEntries() { if(validateAge(document.employee.age.value) == false) { return false; } // additional code checking other entries } Event Handlers Event handler: function that executes as a result of a user action Names of commonly-used event handlers: You can use a JavaScript function as an event handler for a form button onsubmit (for form submit buttons) onclick (for regular command buttons, radio buttons, check boxes, hyperlinks) onselect (for text fields and text areas) onchange (for text fields, text areas, selection lists) onmouseover (for many html elements) Place the event handler name and its associated action directly within the form item tag as an attribute=value The action is usually a JavaScript function call <input type=button event_handler_name="JavaScriptFunctionCall();"> Anonymous Functions Some of the stranger looking code in JavaScript revolves around anonymous functions If used as below not very strange and pretty much interchangeable with non-anonymous functions: Anonymous Functions This anonymous (sort of – it is assigned to sayHello) function works: This doesn't work: Yet this non-anonymous function works: anonymous and non-anonymous functions aren't quite the same Number of other anonymous issues But I'm not going to cover them here We'll return to this when discussing jQuery Examples of Event Handlers <input type="text" name="inputName" value="Joline" onchange="SelectNameText();"> <input type="button" name="showGreeting" value="Show Greeting" onclick="ShowGreetingText();"> <img name=carImage src=car.jpg onmouseover="switchImage();"> Finding Errors (continued) Sources of errors: Error in the command calling the function Misspelled the function name? Wrong capitalization? Forgot the parentheses () after the function name? Error in the function code itself Mismatched curly braces { }? Missing double or single quotes? Wrong spelling or capitalization of commands? ?? What will happen when the button is clicked? Assume browser is set to display errors: A) There must be an error somewhere or you wouldn't be asking this – so an error is displayed B) Hello is displayed C) No error, yet Hello isn't displayed D) No idea what happens… Answer to previous question C – onclick="displayMessage;" should be this: onclick="displayMessage();" Omitting the parentheses after displayMessage doesn't make the browser show an error – yet displayMessage won't be called! What will happen when the button is clicked? Assume browser is set to display errors: A) An error is displayed B) Hello is displayed C) No error, yet Hello isn't displayed D) No idea what happens… Answer to previous question A – function displayMessage { should be: function displayMessage() { Omitting the parentheses after displayMessage in the function declaration does cause a JavaScript error What will happen when the button is clicked? Assume browser is set to display errors: A) An error is displayed B) Hello is displayed C) No error, yet Hello isn't displayed D) No idea what happens… Answer to previous question A – onclick="displaymessage();" should be: onclick="displayMessage();" Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... Topic Validating HTML form inputs determining: If users entered something for required values If users entered correct values Why do this using client-side scripts? Saves time/traffic of sending incorrect/incomplete inputs to the Web server Saves the Web server the processing time needed to validate the inputs? Perhaps not – you should also validate on the server – because users can find ways to submit stuff to the server bypassing JavaScript validation (can you think of one really easy way to do this?) Form Validation Function Function that is called before a form is submitted to the Web server for processing Contains a series of if or if/else tests to determine if form inputs are correct If all inputs are correct, function returns a value of true, and submits the form to the Web server If an input is not correct: function displays an alert to inform the user about the problem sets the focus (or selects – highlights contents) to the input needing attention returns a value of false, and does not submit the form to the Web server Form Validation Function using if Structures function validation_function_name { if (error_condition_1) { alert ("error_condition_1_description"); set_focus_to_input_with_error; return false; } if (error_condition_2) { alert ("error_condition_2_description"); set_focus_to_input_with_error; return false; } if (error_condition_3) { alert ("error_condition_3_description"); set_focus_to_input_with_error; return false; } return true; } Form Validation Function using if/else if Structures function validation_function_name { var ret = false; if (error_condition_1) { alert ("error_condition_1_description"); set_focus_to_input_with_error; } else if (error_condition_2) { alert ("error_condition_2_description"); set_focus_to_input_with_error; } else if (error_condition_3) { alert ("error_condition_3_description"); set_focus_to_input_with_error; } else { ret = true; } return ret; } Is this better than using the previous slide's approach? Strategy for validating values: Steps: Repeat these steps for all other user inputs on the page First check to see if required field value is entered Next check to see if value is of the correct data type (if needed) Finally check for value falling within a specific range (if needed) Work from the top to bottom, left to right as people normally read a page when doing this validation and do all validations for each element as you work from the top to the bottom. When an error is found, notify the user of the error and don’t do further validation until the user corrects this error and resubmits the form. Calling a Form Validation Function Create an onsubmit event handler for the form Syntax: <form name="frmExample" action="nextPage.htm" onsubmit="return Validation_Function_Name();"> Result: If the function returns the value true, the submit input submits the form to the Web server If the function returns the value false, the submit input does not submit the form Caution: If you omit the return before the function name the form will always be submitted – even when false is returned by the function Calling a Form Validation Function (alternate) Create an onclick event handler for the submit button Syntax: <input type="submit" value="Submit" onclick="return Validation_Function_Name();"> Works almost the same as calling from a form's onsubmit Except IE allows a form to be submitted by pressing the Enter key when an <input …> tag is currently selected. If this is done, it bypasses the submit button and the validation function isn't called. Firefox and other browsers don't bypass validation if a submit input's onclick is used. Use the previous slide's form onsubmit approach and do not use a submit button's onclick event. Validating using onblur onblur – event that occurs when the focus shifts away from the currently selected element Allows validating an entry the moment the user tabs or clicks to the next form element Must additionally revalidate all elements when the form is submitted: The user might not tab or click to a required form element and thereby not generate an onblur event Pressing the enter key while an <input …> is selected submits the form if using IE (and doesn't generate an onblur event) Validation – best practice Use onsubmit="return validationFunction();" in your form tag to check entries Consider using onblur to immediately check entries Doing both means more coding effort if time is limited, use onsubmit and omit the onblurs Repeat the validation in the server side program Because users might find way to submit data that bypasses your JavaScript validation What will happen if the user clicks the submit button without entering anything? A) Nothing B) An alert is displayed saying Please enter a number C) An alert is displayed saying Please enter a number and nextPage.htm is displayed D) No alert and nextPage.htm is displayed E) No idea… What will happen if the user clicks the submit button without entering anything? A) Nothing B) An alert is displayed saying Please enter a number C) An alert is displayed saying Please enter a number and nextPage.htm is displayed D) No alert, but nextPage.htm is displayed E) No idea… Validating Numeric Inputs Use the isNaN() function Returns true if the value is not a number An empty string "" will evaluate as false – indicating it is a number (when clearly an empty string is not a number!) So prior to the isNaN() test, add another test to ensure something is entered. Returns false if the value is a number (or is an empty string) Syntax: if (isNaN(document.example.num.value) == true) { alert ("You must enter a value that is a number"); document.example.num.select(); return false; } Validating Numeric and Text Inputs Regular Expressions Syntax: var testNumber = /^[\d]+$/; if(testNumber.test(document.frmCourse.c_credits.value) == false) { alert("Please enter a number for course credits"); document.frmCourse.c_credits.select(); return false; } testName = /^[a-zA-Z]+$/; if(testName.test(example.name.value) == false) { alert("Please enter only letters for your user name"); example.name.select(); return false; } http://gnosis.cx/publish/programming/regular_expressions.html What will happen if the user clicks the submit button after entering a number? A) Nothing B) An alert is displayed saying Please enter a number C) An alert is displayed saying Please enter a number and nextPage.htm is displayed D) No alert and nextPage.htm is displayed E) No idea… Validating Date Inputs There are many ways to do this – none particularly elegant… Use user entry to create a new Date object and test for NaN Write your own custom function to validate the date gets lengthy Use a regular expression to validate the date Doesn't work in all browsers and doesn't do a very good job of validating the date Also lengthy (and cryptic) if you attempt rigorous validation Examples – these aren't complete http://cs.uwec.edu/~morriscm/priv/Spr14/CS268/_ClassNotes/customDateValidationFunction.htm Validating Numeric Ranges Assuming you have already confirmed the user input is a valid number using isNaN, the syntax is: var PIN = parseInt(document.login.UserPIN.value); if (PIN < 1000 || PIN > 9999) { alert("The PIN must be a number between 1000 and 9999"); document.login.UserPIN.select(); return false; } Validating Numeric Ranges Assuming you have already confirmed the user input is a valid number using isNaN and all you care about is that it be a 4 digit number: if (document.frmExample.num.value.length != 4) { alert("The number must have 4 digits"); document.frmExample.num.select(); return false; } Validating Numeric Entry and Length Using Regular Expression Example – requires 4 digit number – it can begin with zeros: rePin = /^[0-9]{4}$/ if(!rePin.test(document.frmName.txtNumber.value)){ Example – requires 4 digit number beginning with 1 or higher: rePin = /^[1-9][0-9]{3}$/ if(!rePin.test(document.frmName.txtNumber.value)){ http://www.zytrax.com/tech/web/regex.htm Order of validation example Top to bottom, left to right (as if reading) The following has top to bottom order Do all validations for name first, then age, then date Assume we only care that "something" is entered for name. Only one validation is needed for name. We need three separate tests to validate age. isNaN won't catch empty entries. And we need to ensure age is in a (somewhat) reasonable range. This regular expression will catch empty entries (no need for a separate test). It doesn't ensure a reasonable range – but I'm not going to require this for this class. mm/dd/yyyy Notice that if an error is discovered, the user is notified without trying to find additional errors. This is avoid overwhelming the user with multiple errors all at once. After fixing the error and resubmitting, additional errors will be brought to their attention. Validating a select list If size="1" (the default value) the first item in the list is always selected by default (until the user selects something else) The selectedIndex of the first item in the list is 0 (zero) If size is greater than 1 (a list instead of a drop down combo box) by default, nothing is initially selected and the initial value for selectedIndex is -1 selectedIndex is what you check to see if something is selected. If it is -1 the user needs to select something. select example: size > 1 so selectedIndex's initial value is -1 (if size == 0 selectedIndex's initial value is 0 and the first item is selected by default) Validating checkboxes First of all, why validate a checkbox? In other instances, there may be no need to validate a checkbox Perhaps you've got a single checkbox at the bottom of the page for the user to check indicating they have read and accept an agreement? (see this all the time) Perhaps there is a list of checkboxes indicating user preferences – and there is no need for a user to check any of them Don't validate unless it makes sense to do so! Validating checkboxes checked property is true if checked Validating radio inputs A group of radio inputs will all have the same name You must check each array element to see if one of them is checked If there are lots of radio inputs in the group – or if the group of radio inputs is generated from a database query and you don't know how many will be generated: Use a loop to process the array storing the radio inputs and see if one is selected Validating radio inputs (without using a loop) Look at each array element individually to see if checked. In this example there are only two elements in the group. Validating radio inputs (using a loop – assume there are "lots" of choices in the radio group color) The length property stores how many elements are in the array If any element in the array is checked there is no need to continue looking – there can only be one selected (checked) element in a radio group. If index is still -1, a checked radio input wasn't found in the array Dreamweaver’s form validation Dreamweaver will automatically generate a Javascript function to validate form inputs Dreamweaver allows you to: Specify required fields Specify that field data types must be numbers Specify number ranges Dreamweaver Pros and Cons Pros? Easier and faster to add a script! Cons? You lose control of Message text Selecting the input with the error Can't validate dates Single alert displays message about each error (is this good?) Nasty looking JavaScript – care to modify the generated code? Dreamweaver Generated JavaScript Easy to understand and modify this code – no? Similar code rewritten for human eyes Easy to understand and modify this code (including features Dreamweaver can't add – yes!) Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... Debugging JavaScript Programs What happens when a script fails? Whatever it was supposed to do doesn't happen No error messages unless the browser you are using is configured to show the error(s) All of the major browsers now have decent JavaScript debugging tools built in. I'll show a few in class All browsers cache cookies and pages For example: Firefox – enter about:cache in the address bar: Make sure you aren't viewing a cached page that doesn't have your changes in it! When using Firefox, press Ctrl-F5 at the same time to make Firefox get a new page instead of using its cache. Finding Errors – when the error console isn't enough Strategies Determine if the function is actually getting called Display a short alert message as the first line of the function If the function is getting called, then determine which line is crashing Display a short alert before every line to see how far you are getting or Cut out approximately half of the code and see if the error still occurs. If it does, the error is in the remaining half, if not, the error is in the half you cut out. When cutting out code save it somewhere so you can add it back after you find the error. Be careful where you cut the code. You can introduce new errors if you cut in a way that introduces mismatched curly braces or splits a string constant across two lines. Topics Introduction to JavaScript Positioning a script Variables Type conversions Concatenation HTML forms Document Object Model Functions Form Validation Debugging Stuff... Displaying a Confirm Message • Confirm message is similar to an alert – but it has an OK and a Cancel button Examples using confirm Alternate and equivalent code: The following code segments are equivalent: A) Yes B) No C) Don't know… Changing the window location Doesn’t open a new window, changes location of current browser window window.location.href = "new URL" Examples: window.location.href = "http://www.google.com" window.location.href = "orders.htm" window.location.href = "..\products\catalog.htm" window.open Pop up ad blockers will block a window.open command from events other than the onclick event window.open called from an onclick event is allowed by most pop up blockers. Blocked <body onload="window.open('advertisement.html');"> <img src="drgdx.gif" onmouseover="window.open('advertisement.html');"> Not blocked <input type="button" value="Open Window" onclick="window.open('advertisement.html');"> <img src="drgdx.gif" onclick="window.open('advertisement.html');"> Opening a new window var window_id = window.open(url, [name, [options, [replace] ] ]) var window_id = is optional – if used, window_id can be used to close, resize, or move the new window to a different spot on the screen. url is optional – if omitted a blank browser window is displayed name is optional – What happens if you execute the window.open() method twice, with the same name (also called target) argument? Like HTML-generated windows, if you specify the name of a window that already exists, open() simply uses that existing window rather than opening a new one. options – define the properties of the new browser window replace is optional - If true, the new location will replace the current page in the browser's navigation history. Note that some browsers will simply ignore this parameter Opening a new window Option list parameters toolbar displays the browser toolbar toolbar=yes toolbar=no location displays the address field in the browser location=yes location=no directories displays the window title bar links to frequently used URLs directories=yes directories=no status displays the status bar at the bottom edge of the window status=yes status=no menubar displays the browser menu bar menubar=yes menubar=no scrollbar displays scrollbars on the browser scrollbar=yes scrollbar=no resizable allows the user to resize the browser window resizeable=yes resizeable=no width, height specifies the browser window width and height, in pixels width=300 height=200 Opening a new window Example var wParams = "height=160,width=550,menubar=no,toolbar=no,titlebar=no," + "resizable=no,location=no,status=no,directories=no"; var adWindow = window.open("ad.htm","",wParams); adWindow.moveTo(230, 350); Arrays Code creating an array and retrieving it’s contents: <script> var classes = new Array(); classes[0] = "CS 491"; classes[1] = "CS 352"; classes[2] = "CS 319"; classes[3] = "CS 163"; function displayClasses() { for (var i = 0; i < classes.length; i++) { document.write(classes[i] + "<br>"); } } </script> Arrays HTML input elements are stored as arrays Example : function DisplayElements() { var msg = ""; for(var i = 0; i < document.frmOrderItem.elements.length; i++) { msg += document.frmOrderItem.elements[i].name + "=" + document.frmOrderItem.elements[i].value + "\n"; } alert(msg); } Arrays Radio inputs are in arrays Validating a radio input is checked sometimes requires array processing function ValidateRadioSelected() { var index = -1; for(var i=0; i<document.frmOrderItem.color.length; i++) { if(document.frmOrderItem.color[i].checked) { index = i; break; } } if(index >= 0) { alert(document.frmOrderItem.color[index].value + " is checked"); return true; } else { alert("Please select a color"); document.frmOrderItem.color[0].focus(); return false; } } window.setTimeout Can omit the window. Executes Javascript commands after a specified amount of time elapses setTimeout("commandOrFunction", timeToWaitInMilliSeconds); setTimeout("alert('5 seconds have elapsed')", 5000); window.setInterval Similar to setTimeout – except will continue to execute the command(s) again and again after the specified time elapses. setInterval(commandOrFunction, timeToWaitInMilliSeconds); setInverval(alert("5 seconds have elapsed"), 5000); http://ejohn.org/blog/how-javascript-timers-work/ window.screen Useful to center browser window in the screen But only if you opened the window using window.open Can be used to download smaller images to browsers with lower color depths or resolution Which could make page downloads faster But this is a lot of work and normally isn't done screen.height screen's height in pixels screen.width screen's width in pixels screen.colorDepth #bits used to display color What will this do? Here's the code as text if you want to copy and paste it in a new page and then test it to see what it does <html><head><title>What does this do?</title> <script> var x = 0; var y = 0; var direction = "down"; var winID; function initializeBrowser() { var wParams = "height=200,width=400,top=0,left=0"; winID = window.open("", "", wParams); setInterval('moveBrowser()', 1); } function moveBrowser() { if(direction == "down" && y > screen.availHeight - 200) { direction = "up"; } else if(direction == "up" && y < 50) { winID.close(); this.close(); } if(direction == "down") { x += 4; y += 4; } else { x -= 4; y -= 4; } winID.moveTo(x, y); winID.focus(); } </script> </head> <body> <input type="button" onclick="initializeBrowser();" value="Start"> </body></html> JavaScript Events Ways to assign inline (works in all browsers): <input type="button" onclick="myFunction();"> traditional (using JavaScript – works in all browsers): obj = document.getElementByID("relevantID"); obj.onclick = myFunction; W3C (JavaScript – can add several event listeners to the same event for the same object): obj = document.getElementByID("relevantID"); obj.addEventListener('click', myFunction, false); Microsoft (JavaScript): obj = document.getElementByID("relevantID"); obj.attachEvent('click', myFunction, false); http://www.quirksmode.org/js/introevents.html JavaScript Events If you use the traditional method (works in all browsers) declare function with a single parameter (any name will do but e is often used) function myFunction(e) { … } Parameter references the event object in browsers OTHER than IE If using IE parameter is ignored IE references the event object using window.event Detecting browser (and type of code to use) if(window.event) { // IE } or if(e) { // not IE – assumes named parameter e } JavaScript Events Event object properties/methods Varies between IE and rest of world The following link lists many of them: http://www.javascriptkit.com/domref/domevent.shtml JavaScript Events Recommendation? Use traditional rather than inline if you need access to the event object Useful to prevent Firefox from automatically doing drag and drops with images Some say use it all the time Separates code from html markup Allows access to the event object (IE always allows access - other browsers need an e parameter) But – results in more complicated code see next slide JavaScript Events Less code – and less complicated JavaScript Events Wait until page finishes loading to initialize the events Retrieve the element and assign a function to relevant events I'm not showing it, but you will need to pre-cache the images Retrieve the element triggering the event. Code varies between IE and rest of world Recent Firefox versions automatically drag all images when mouse is pressed and dragged over the image. IE throws an error over this code. Other browsers just ignore it. This prevents Firefox from dragging the image. See next slide for revised way to do this. Block image dragging What is the result? A. B. C. Name was Smith Name was not Smith Same as previous question, you didn't change a thing Pitfall: Using = or == ' = ' is the assignment operator Used to assign values to variables Example: var name = "Smith"; '= = ' is the equality operator Used to compare values Example: if ( name == "smith") Javascript will accept this error: if( name = "smith") but stores smith in name instead of comparing name and "Smith" Since the result is "Smith" (non-zero and also not an empty string ""), the expression is considered true any result besides an empty string or 0 is considered true a result of 0 or "0" or "" is considered false Always use == to compare and you won't have to worry about this!