JavaScript II Retrieving Information from a Form Variables & Data Types Y. Mendelsohn.

Slides:



Advertisements
Similar presentations
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Advertisements

Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
PHP : Hypertext Preprocessor
The Bean Counter: A JavaScript Program
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
CSC 330 E-Commerce Teacher Ahmed Mumtaz Mustehsan Ahmed Mumtaz Mustehsan GM-IT CIIT Islamabad GM-IT CIIT Islamabad CIIT Virtual Campus, CIIT COMSATS Institute.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #002 (January 17, 2015)
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
What is Java Script? An extension to HTML. An extension to HTML. Allows authors to incorporate some functionality in their web pages. (without using CGI.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
Return values Efficiency in Coding. Learning Objectives By the end of this lecture, you should be able to: – Be able to apply an ‘object literal’ when.
1 JavaScript
Introduction to JavaScript CS101 Introduction to Computing.
1 A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 4 JavaScript and.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
Introduction to Computer Programming 2. Program Structure I - 1http:// Program Structure I (Overview) Handling of Values – The.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
1 JavaScript and Dynamic Web Pages Lecture 7. 2 Static vs. Dynamic Pages  A Web page uses HTML tags to identify page content and formatting information.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
Precedence Operators Error Types
Moving away from alert() Using innerHTML Using an empty div section
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Chapter 6 JavaScript: Introduction to Scripting
Concatenation Comments
JavaScript is a programming language designed for Web pages.
Arrays: Checkboxes and Textareas
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
Variables, Expressions, and IO
Introduction to Scripting
Retrieving information from forms
Arrays and files BIS1523 – Lecture 15.
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
Intro to PHP & Variables
Introduction to JavaScript
Web Programming A different world! Three main languages/tools No Java
Conditions and Ifs BIS1523 – Lecture 8.
Number and String Operations
WEB PROGRAMMING JavaScript.
JavaScript – Part I Mendelsohn.
INFO/CSE 100, Spring 2005 Fluency in Information Technology
T. Jumana Abu Shmais – AOU - Riyadh
Introduction to TouchDevelop
INFO/CSE 100, Spring 2006 Fluency in Information Technology
JavaScript Variables.
Introduction to JavaScript
Tutorial 10: Programming with javascript
JavaScript Basics What is JavaScript?
Unit 3: Variables in Java
PHP-II.
Web Programming and Design
Modifying HTML attributes and CSS values
JavaScript Variables.
Random Stuff Colors Sizes CSS Shortcuts.
Retrieving information from forms
Introduction to scripting
JavaScript Variables.
Adios alert() Using innerHTML Using an empty section
Presentation transcript:

JavaScript II Retrieving Information from a Form Variables & Data Types Y. Mendelsohn

Retrieving information from a form At this point, the most important technique to become familiar with is how to use JavaScript to retrieve information from a form. Fortunately, the commands are generally pretty straight-forward. Things work a bit differently (and are a little trickier) for certain elements such as radio buttons and checkboxes.

* Retreiving the value of a form element from a page: To retrieve information entered in a textbox, the syntax is: document.form-name.element-name.value; Eg: document.pizzaOrder.txtFirstName.value; * Will retrieve the value from a textbox called ‘txtFirstName’ in a form whose name is ‘pizzaOrder’ Eg: document.regForm.selNationality.value; Eg: document.userInfo.textarComments.value;

*Using “variables” to store information The downside to the retreival command is that the information we’ve read isn’t stored anywhere. So, we need a method of storing information. The technique for doing this is something called a variable. Here is the JavaScript code to declare a variable and to store a form value inside of it: var userName; userName = document.form1.txtFirstName.value;

Using variables to store information contd: 1. var userName; 2. userName = document.form1.txtFirstName.value; The first line is called declaring the variable. You must always declare a variable using the command ‘var’ followed by the name of the variable (which you can choose). In the second line, we assign the value retrieved by the form to that variable.

Using variables to store information Some more examples: var firstName, lastName, age; //Declaring several variables on one line is OK var comments; firstName = document.form1.txtFirstName.value; lastName = document.form1.txtLastName.value; age = document.form1.txtAge.value; comments = document.form1.txtarComments.value;

3x1 hour v.s. 1x3 hours: Nothing in this discussion is very difficult. However there are several details to learn. The only way you’ll understand and develop at least some comfort with a concept is by practicing. Take these lecture notes and type in the examples yourself. For any concept you are trying to learn, do this SEVERAL times each week. There is simply no comparison between reviewing something 3 times for one hour v.s. 1 time for 3 hours!! The ability to understand and retain information is significantly better if you do your first review session within 12 hours of a lecture.

Variables can store just about anything: Variables will be used in nearly every bit of programming that you will do. Variables are used to store values (eg. Strings, Numbers) You can directly assign values to a variable. That is, you are not required to assign a value from a form Here are a few variables all of which have been directly assigned values. var temperatureCelcius, temperatureFarenheit,; var userName, userAge; temperatureCelcius = 33; temperatureFarenheit = (9.0 / 5 * temperatureCelcius)+32; userName = “John Doe”; userAge = 47;

* STRINGS: Storing a String in a Variable: A combination of letters / words / symbols, etc is called a “String”. Strings are always placed in double quotes. Some examples of Strings: “Robert Smith” “Hello, how are you today? I am fine!!!” “12345”  (a string of digits – NOT a number!!) “#$@(~?%(*^%#$”  a string of random characters “”  (an empty string) var userName, telephoneNumber, favoriteBand; userName = “John Doe”; telephoneNumber = “800-867-5309”; favoriteBand = “Jonas Brothers”; (not really)….

* Using a mathematical formula in a variable: var temperatureCelcius, temperatureFarenheit; var miles, kilometers; temperatureCelcius = 33; temperatureFarenheit = (9.0/5* temperatureCelcius )+32; // the decimal after 9 is needed //will explain more in a later lecture miles = document.form1.txtMiles.value; kilometers = miles * 1.6;

* Outputting variable values to a web page You can use the document.write command to output the values of a variable to a web page. Inside a document.write statement, you can also intersperse strings with variables as shown below. Notice the use of ‘+’ to separate strings and variables. var firstName, lastName, age; firstName = document.form1.txtFirstName.value; lastName = document.form1.txtLastName.value; age = document.form1.txtAge.value; alert("Dear " + firstName + " " + lastName + "."); alert("You are " + age + " years old.");

* Concatenating Strings You can add as many strings together as you like using the ‘+’ operator: alert("H" + "e" + "l" + "l" + "o"); You can intermix strings and variables – very common – learn this! var name="Bob"; alert("Hello, " + name); alert("Hello, " + name + ", how are you?");

* The document.write function document.write will write whatever is inside quotes to your HTML page. This includes your usual HTML markup. document.write("Hello"); document.write("<h1>Hello</h1>") document.write("<center>DePaul University</center>"); You can add as many strings together as you like using the ‘+’ operator: document.write("H" + "e" + "l" + "l" + "o"); You can intermix strings and variables – very common – learn this!: var name="Bob"; document.write("Hello, " + name); document.write("Hello, " + name + ", how are you?"); How would you take the last line and put the name in bold and italics? document.write("Hello, <strong>" + name + "</strong>, how are you?");

Testing JS Using your browser’s ‘BACK’ button When a JS responds to a form, a new page will often be displayed on your browser. To refresh your form, simply pressing ‘refresh’ will usually NOT give you the results you want. This is because you are simply refreshing the page that resulted from your form rather than the form itself. That is, you are on a new page. For this reason, you need to press ‘BACK’ to get to your original form (and then press ‘refresh’).

Reivew: Creating Variables – “Declaring” You must always DECLARE a variable before you can use it. Note: You only declare a variable ONCE in your code! Once a variable has been declared, you can use it as many times as you want.

Creating Variables contd: We can declare a variable and assign it a value in the same line: var age = 34; // A useful shortcut… This is a very common and important syntax – Be familiar with it!!

Naming your variable: A variable name must be a sequence of letters digits A variable can NOT: Begin with a digit Have a space Have mathematical operators such as: +, -, /, *, %, etc Have various other characters such as & ^ : Remember: JavaScript is case sensitive so “firstName” and “FirstName” are different variables.

Exercise Which of the following are legal variable names? Why? fav_movie You&I first Name http:// 3rd_number aLongVariableName x legal illegal: cannot contain & illegal: cannot contain a space illegal: cannot contain : or / illegal: cannot begin with a digit legal legal

Another Kind of Value <script type="text/javascript"> var foo; document.write(foo); </script> What do you think will happen? 19

* “undefined” or NaN Exam question(s) are likely on this… ‘undefined’ is the default value of a variable when it is created. NaN stands for “Not a Number” You can declare a variable without giving it a value. This is not an error. However to USE the variable (e.g. in a calculation, to output it to the screen), it must have a value. If you use (e.g. output) a variable without giving it a value, you will get an error, or, nothing will be output. var x; document.write(x); Keep in mind that undefined is not the same as 0. 20

Try it: The computer will assume that hello is the name of a variable <script> document.write(hello) </script> What will happen? The computer will assume that hello is the name of a variable It will try to write the value of hello to the web page If it can’t, it will give an error, or, simply ignore the code. What about document.write("hello"); ?

Review of the + operator When used with strings, ‘ + ’ concatenates them: var val1 = "Hello"; var val2 = "there"; var val3 = val1 + val2; var val4 = val3 + "45"; document.write(val4); Input two (or more) string values Output Concatenated version of the individual values 22

Review of the + operator contd: When used with numbers, ‘ + ’ mathematically adds them: var n1 = 10; var n2 = 5; document.write(n1 + n2); //will output 15 Input two (or more) numeric values Output Mathematical sum of the values 23

* A heads-up Because document.write statements essentially create a new page on the browser, document.write statements should be the last part of your JS. In other words, don’t have some document.write statements at the beginning of your code, then read some input from the form, then more document.write statements, then a calculation, the more document.write statements, etc. Save all the document.write statements for the end of your script.

Storing form data inside variables Let’s practice by taking all of the data from a form and storing it inside variables: Create a form with text boxes for first name, last name, age. Write a JS that reads the values from those fields and stores those values into variables. Name the variables fn, ln, age Write a “confirmation screen” that thanks the user for entering their information and confirms what they wrote. Use some HTML formatting (e.g. H2 tags, etc) in your confirmation screen. See next slide for desired result.

The form: After the user submits the form:

Code: My version called ‘userInfo.htm’ can be found on the class web page.

CSS inside document.write Suppose you want to output the following HTML using document.write statement: The crazy <span style="color:brown; font-weight:bold">brown</span> fox. You might think that the correct document.write statement would be: document.write("The crazy <span style="color:brown; font-weight:bold">brown</span> fox."); However, this will NOT work!! Can you figure out why?

“Escaping a character” Recall how whenever you have an attribute/vaue pair, you must surround the vaue with quotes. If, however, you are inside a document.write statement, the quotes used to surround the value are treated as the quotes you need for a document.write statement. In the example below, the quote in red is the culprit… document.write("The crazy <span style="color:brown">brown</span> fox...); Fortunately, there is an easy way to tell the JS interpreter to NOT treat the quote as a JS character. That way is to place a backslash before the character. So the proper way to write the line above is: document.write("The crazy <span style=\"color:brown\">brown</span> fox...);

The Key Point: Any quote or other special character that is part of your HTML (not Javascript) might be mistaken as JavaScript. The two most important ones are: Quotations " Semicolons ; There are others – if a script suddenly stops working, on thing to look for is a missing escape character SO: If you are writing HTML using Javascript (e.g. via a document.write statement), every special character in your HTML that might be confused with JS should be escaped with a backslash. It is not a problem to escape a normal character. So if you’re not sure, go ahead and escape it – just don’t go overboard! Eg: alert("\h\h\e\l\l\o\!\!\!");  Won’t hurt anything, but very un-clear!

* Easiest way to do it: Go ahead and simply throw all the HTML inside a document.write statement. Don’t worry about special characters yet… document.write(" <h1 style="color:red; background-color:blue">Some H1 text…</h1> "); Then carefully go through the statement and look for any HTML symbols (quotes, semicolons, etc) that might interfere with JS. Then put your escape character before any problematic character. document.write(" <h1 style=\"color:red\; background-color:blue\">Some H1 text…</h1> ");

Try It: Create a new page, and using ONLY document.write statements try outputting the following HTML: <h1>Hello!!!</h1> document.write("<h1>Hello!!!</h1>"); <h1 style="color:#339900">More H1…</h1> document.write("<h1 style=\"color:#339900\">More H1…</h1>"); <img src="airlane.jpg" alt=\"Pic of Plane\" /> document.write("<img src=\"airlane.jpg\" />"); <a href="http://www.depaul.edu"> DePaul </a> document.write("<a href=\"http://www.depaul.edu\"> DePaul </a>");

Try One More: Using ONLY document.write statements try outputting the following HTML: <h2 style=\"color:#339900\; font-style:italic\">Some text</h2> document.write("<body style=\"color:#339900\; font-style:italic\">"); In this case, you might have forgotten to escape the semicolon separating the property from its value. To summarize: When typing HTML code using JavaScript, any symbol that is present but is NOT part of the JS (e.g. is part of the HTML) should be escaped with a backslash.

Another Lab Exercise: Let’s write a form that calculates the “Body Mass Index” used in fitness circles as a quick (though not entirely accurate) indicator of a person’s health. The formula requires the user to enter their height and weight and then calculates their BMI. The formula is: weight in pounds* 703 divided by height in inches squared. BMI = (weight*703) / (height*height)

After the user submits the form: The formula for BMI is Weight*703 / (height*height) After the user submits the form: Don’t forget that you need to click the browser’s ‘Back’ button to return to your form.

START SIMPLE and gradually BUILD Creating the BMI form START SIMPLE and gradually BUILD Create the form THEN Write the basic outline of your JS function THEN: Test the function by outputting something very simple such as “test” THEN Retreive the values from the form and store them in variables. Output those variables to make sure you have done it correctly. THEN incorporate the formula. THEN: Worry about the visuals. (e.g. colors, graphics, reducing the number of decimals in the BMI, etc) Etc

Code: My version called ‘bmi_calc.htm’ can be found Don’t confuse with bmi_calc_class.htm  that’s coming later… You can learn more about the application of BMI to your health here.