1 / 114

Javascript

Learn the fundamentals of Javascript, a scripting language embedded in HTML code, to create dynamic web pages. Topics include variables, dialog boxes, data types, objects, arrays, and functions.

bessiea
Download Presentation

Javascript

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. Javascript Cyndi Hageman

  2. Javascript Basics • 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.

  3. Javascript Basics • Case sensitive – an object named “txtFirstName” is different than “txtFirstname” 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.

  4. Javascript Basics • 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. • 12 is the number 12 • “Hello World” is a string of text • true is the boolean value true • null is the absence of value

  5. Javascript Basics • 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.

  6. Simple Dialog Boxes • 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.

  7. Simple Dialog Boxes • 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.

  8. Examples of Dialog Boxes • 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:”,””);

  9. Variables • 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. var i; var val; var i, val;

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

  11. Primitive Data Types • 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.

  12. Composite Data Types - Objects • An object an be an unordered collection of named values. These are often referred to as the properties of that object. • 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.form1.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”);

  13. Composite Data Types - Objects • An object can be an ordered collection of numbered values. These are called arrays. • 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);

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

  15. Functions cont. • Functions accept arguments or parameters • 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. • Function Math.round(x) requires one argument. This argument should be a number type so the math function can be performed.

  16. null and undefined • 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.

  17. isNaN • There is a special javascript function you can use to determine if a value is a number or not. • If isNaN(x) returns true, then the number passed is not a number. It is a string or a boolean. • If isNaN(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.

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

  19. Data Type Conversion • Other methods for converting numbers to strings: var n=123456.789 • n.toFixed(0); //”123457” • n.toFixed(2); //”123456.79” • n.toExponential(1); //”1.2e+5” • n.toExponential(3); //”1.235e+5” • n.toPrecision(7); //”123456.8”

  20. Data Type Conversion • Strings to Numbers: • 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);

  21. Data Type Conversion • parseInt() can be used to retrieve an integer at the beginning of a string:parseInt(“3 blind mice”) //returns 3parseInt(“12.34”) // returns 12 • parseFloat() can be used to retrieve integers and floating point numbers in a string:parseFloat(“3.14”) //returns 3.14parseFloat(“12.5 meters”) //returns 12.5

  22. Data Type Conversions • If parseInt() or parseFloat() cannot convert a string to a number, it returns NaN • parseInt(“eleven”) //returns NaN • parseFloat(“$54.45”) //returns NaN

  23. Data Type Conversion • Javascript will automatically convert boolean values: • 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 NaN is automatically converted to true, 0 or NaN is converted to false • Explicitly convert by using Boolean() function:var booleanvalue = Boolean(x);

  24. Variable Scope • Region in a program in which a variable is defined • 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.

  25. Scope example <script language = “javascript”> var val; function getvalues(value1, value2) { var newvalue; } function setvalues(value1, value2) { newvalue = value1; val = value2; } </script>

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

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

  28. Order of Precedence • Arithmetic equations are read from left to right • 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.

  29. 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

  30. 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--;

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

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

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

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

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

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

  37. Examples if ((x > y) && (n > m)) if ((x == y) && (n > m)) if ((x == y) || (n > m)) if ((x > y) || (n > m)) if ((x ==y) || (n==m))

  38. else • 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 • if (condition){ //executes if condition is true}else{ //executes if condition is false}

  39. else if • Combines the else statement with another if evaluation • if (condition){ //executes if condition is true}else if (condition2){ //executes if condition2 is true}else{ //executes if condition and condition2 are false}

  40. switch statement • 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.

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

  42. while • 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. • while (condition){ //executes while condition is true}

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

  44. do while • 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. • do{ //executes the first time thru and will continue to execute as long as the while condition evaluates to true} while (condition)

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

  46. for loop • 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: • The counter variable initialized • The condition • The counter variable updated for each loop

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

  48. break • 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.

  49. 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; } }

  50. continue • 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

More Related