1 / 37

JavaScript II Retrieving Information from a Form Variables & Data Types

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

ifama
Download Presentation

JavaScript II Retrieving Information from a Form Variables & Data Types

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 II Retrieving Information from a FormVariables & Data Types Y. Mendelsohn

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

  3. * 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;

  4. *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;

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

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

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

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

  9. * 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)….

  10. * 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;

  11. * 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.");

  12. * 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?");

  13. * 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?");

  14. Testing JSUsing 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’).

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

  16. 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!!

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

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

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

  20. * “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

  21. Try it: <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"); ?

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

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

  24. * 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.

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

  26. The form: After the user submits the form:

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

  28. 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?

  29. “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...);

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

  31. * 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. document.write(" <h1 style="color:red; background-color:blue">Some H1 text…</h1> "); • Then put your escape character before any problematic character. document.write(" <h1 style=\"color:red\; background-color:blue\">Some H1 text…</h1> ");

  32. 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>");

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

  34. 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)

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

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

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

More Related