Lecture 9   Class Activities for Forms, Functions and Events

  • Assumptions about how this course works
  • Google is your friend.
  • Exam next week
  • SI sessions and review
  • no calculators on the exam; expressions okay for some answers

Variables

One of the important features of almost all programming languages is the ability to store a value so that it can be used later. These are called variables.

There are rules for how they can be created and named. Here are the rules for JavaScript:

  • Create them with var. JavaScript allows this to be optional, but you should not.
  • The name should start with a letter, contain letters, numbers, and maybe underscores, but nothing weird and no spaces.
  • The name can't be a special part of the language, such as var, or function or if, etc. These are reserved.

Make your variable names intuitive: they should remind you of the stuff stored in them, so user_age is good, but n or stuff is not.

Quiz Question Nr. 1

What does the following statement do?

x = y;
  1. It gets an error

  2. It tests whether the two variables are equal

  3. It copies the value of y into x

  4. It copies the value of x into y

Getting Data

In this course, variables will almost always get their values from

  1. other variables and expressions
  2. a user input function (mostly for testing)
  3. a form

Quiz Question Nr. 2

We want some code that will ask the user their name and greet them. Which of the following does that?

  1. var user = alert("what's your name?");
    prompt("Greetings, "+user);
    
  2. var user = prompt("what's your name?");
    alert("Greetings, "+user);
    
  3. var user = prompt("what's your name?");
    var greet = "Greetings, "+user;
    alert(greet);
    
  4. var user = alert("what's your name?");
    var greet = "Greetings, "+user;
    prompt(greet);
    

There's a pattern to that kind of code:

  1. Get some input
  2. process it, deriving some result
  3. report the result

Not all of our code will show that pattern, but it often will, so it's worth stepping back to see the pattern.

Forms and the DOM

Forms allow the user to supply the information we want on their schedule, skipping around and ignoring inputs. That's much better than a series of prompts.

We can access anything in the document from JavaScript using the Document Object Model or DOM. The DOM is just a collection of stuff added to the JS language that lets us poke around in the document, finding the parents and children of nodes, and even modifying the document.

We can also find out dynamic info like the value of an input in a form.

Here's an example form:

  <form>
    <p> height in feet
      <input type="number" id="height_feet" name="height_feet"> and 
      <input type="number" id="height_inches" name="height_inches">.
    <p> <button type="button" id="convert_button">convert to metric</button>
    <p> <button type="button" id="student_button">student button</button>
  </form>

height in feet and .

You're welcome to click the first button and see how the form works. Later today, you'll define the behavior for the second button.

Exercise 1

With a partner, do the following. I expect this exercise to take a while, maybe 20 minutes or more, so don't feel you have to rush.

  1. Write some JS/JQ code to extract the values of the two form inputs. You should test this in the JS console, by filling out the form and seeing those values in the console.
  2. Store the two values in variables.
  3. Make sure the values are numbers and not strings
  4. Compute the total number of inches. That should probably be another variable.
  5. Report the result in some way, such as alert or console.log.
  6. Compute the number of centimeters. That should probably be yet another variable.
  7. Report the value.
  8. Compute the number of meters, in one last variable.
  9. Report this last value.

Quiz Question Nr. 3

Did you get it to work? How far did you get?

  1. Got stuck on step 1

  2. Got stuck on step 2

  3. Got stuck on step 3

  4. Got stuck on step 4 or 5

  5. Got stuck on step 6 -- 9

  6. Complete success!!

Functions

A function allows us to package up a chunk of code and give it a name. We can run that code later by invoking (or calling) the function.

We define a function like this:

    function name_of_function () {
        // body of function
    }

    function yo () {
        console.log("Hey there!");
    }
  

We invoke a function using its name and parens:

    yo();
  

Exercise 2

Using the JS console, trying invoking yo. Try defining a different function called greet that packages up the code from question Nr. 2.

Function to Convert Pounds

The code of a function can be (pretty much) any JS code, so it can get values from a form. Here's an example:

Enter a weight in pounds:

  <form>
    <p>Enter a weight in pounds:
      <input type="number" id="weight_lbs" name="weight">
      <button type="button" id="convert_button2">convert to metric</button>
  </form>
  
    function convertPounds () {
       var lbs = parseInt($("#weight_lbs").val());
       var kg = lbs / 2.2;
       alert("In kilos, that is "+kg);
    }
  

Exercise 3

Using the JS console, fill out the pounds form and then invoke convertPounds.

Then, return to your code from exercise 1 and package it up into a function. Fill out the form and invoke the function.

Event Handlers

Another cool thing about functions is that they can be attached to an element in the document, and then the browser can invoke them when an event occurs involving that element. This makes the function an event handler.

We can attach a function to an element using jQuery's .click() method. That makes the function an event handler for events involving the user clicking on that element.

Here's an example.

weight in kilos: height in meters:

Here's the HTML:

  <form>
    <p>weight in kilos:
      <input type="number" id="weight_kg" name="weight_kg">
      height in meters:
      <input type="number" id="height_meters" name="height_meters">
      <button type="button" id="bmi_button">compute BMI</button>
  </form>

Let's define a function to compute the BMI. Note the use of parseFloat instead of parseInt, to allow people to enter a height of, say, 1.7 meters. We could also allow people to enter their weight using floating point as well, but forcing them to round off to the nearest kilo isn't so bad.

    function compute_BMI () {
       var weight = parseInt($("#weight_kg").val());
       var height = parseFloat($("#height_meters").val());
       var bmi = weight/(height*height)
       alert("The BMI is "+bmi);
    }
  

Let's attach that function to the button:

    $("#bmi_button").click(compute_BMI);
  

Exercise 4

Return to your code from exercise 3 and attach the function to the student_button.

Modularity

The conversion functions we defined today are closely tied to the forms that provide the input. That's okay, but there's a better way.

Later in the course, we'll learn how to define generic functions that do, for example, metric conversions for us, on any data. We'll then be able to use those generic functions to create, say, a form that computes BMI using archaic units, without copy/pasting the conversion code.

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Thursday, 13-Oct-2016 20:23:19 EDT

Solutions

Quiz question #1 is C.

Quiz question #2 is B or C.

For exercise 1:

          var feet = parseInt($("[name=height_feet]").val());
          var inches = parseInt($("[name=height_inches]").val());
          var total_inches = 12*feet+inches;
          alert("total inches:" + total_inches);
          var cm = 2.54 * total_inches;
          alert("cm:" + cm);
          var meters = cm/100;
          alert("meters:" + meters.toFixed(2));
      

Quiz question #3 is F.

For exercise 2:

	function greet() {
	  var user = prompt("what's your name?");
          alert("Greetings, "+user);
        }
      

For exercise 3:

      function convertHeight () {
          var feet = parseInt($("[name=height_feet]").val());
          var inches = parseInt($("[name=height_inches]").val());
          var total_inches = 12*feet+inches;
          alert("total inches:" + total_inches);
          var cm = 2.54 * total_inches;
          alert("cm:" + cm);
          var meters = cm/100;
          alert("meters:" + meters.toFixed(2));
      }
      

For exercise 4:

         $("#student_button").click(convertHeight);