Gots N' Needs Notecards

Gots: On one side of the notecard write what you feel like you "got" so from doing Homework Assignment 2 and CP 2.

Needs: the other side of the notecard, write something you feel you still need to understand, or that would help you understand this material.

CSE 154

Lecture 9: Forms and Events

What we've Covered in JavaScript so Far

Types (Strings, Numbers, Arrays)

Conditionals, Loops, Functions

Modular JS Pattern

Basic Event Handlers

Today: More Events, Forms, Timers, and Animations

More HTML input types

Table of HTML Form Elements

The following is a (partial) list of HTML form elements. For more information on form elements, make sure to check W3Schools.

<input>

	            
	            <!-- 'q' happens to be the name of Google's required paramter -->
	            <input type="text" name="q" value="Colbert Report" />
	            <input type="submit" value="Booyah!" />
	          

HTML

Input element is used to create many UI controls (an inline element that must be self-closed

name attribute specifies name of query parameter to pass to server

type can be button, checkbox, file, hidden, password, radio, reset, submit, text, ...

value attribute specifies control's initial text

<input> Text Fields

	            
	              <input type="text" size="10" maxlength="8" /> NetID <br />
	              <input type="password" size="16" /> Password
	              <input type="submit" value="Log In!" />
	            

HTML

NetID
Password

output

input attributes: disabled, maxLength, readonly, size, value

size attribute controls onscreen width of text field

maxlength limits how many characters the user is able to type into the field

Text boxes: <textarea>

	            
	              <textarea rows="4" cols="20">
	              Type your comments here.
	              </textarea>
	          

HTML

output

Initial text is placed inside textarea tag (optional)

Required rows and cols attributes specify height/width in characters

optional readonly attribute means text cannot be modified

Checkboxes: <input>

yes/no choices that can be checked and unchecked (inline)


	           Lettuce
	           Tomato
	           Pickles
	          

HTML

Lettuce Tomato Pickles

output

None, 1, or many checkboxes can be checked at same time

When sent to server, any checked boxes will be sent with value on:

  • http://webster.cs.washington.edu/params.php?tomato=on&pickles=on

Use checked="checked" attribute in HTML to initially check the box

Radio buttons: <input>

sets of mutually exclusive choices (inline)


	           Visa
	           MasterCard
	           American Express
	          

HTML

Visa MasterCard American Express

output

Grouped by name attribute (only one can be checked at a time)

Must specify a value for each one or else it will be sent as value on

Text labels: <label>


	          
	          

HTML

Grouped by name attribute (only one can be checked at a time)

Must specify a value for each one or else it will be sent as value on

Drop-down list: <select>, <option>

menus of choices that collapse and expand (inline)


	          
	          

HTML

output

Option element represents each choice

Select optional attributes: disabled, multiple, size

Optional selected attribute sets which one is initially chosen

Using <select> For Lists


	          
	          

HTML

output

Optional multiple attribute allows selecting multiple items with shift- or ctrl-click

Must declare parameter's name with [] if you allow multiple selections

Option tags can be set to be initially selected

Option Groups<optgroup>


	          
	          

HTML

output

What should we do if we don't like the bold appearance of the optgroups?

Grouping Input: <fieldset>, <legend>

groups of input fields with optional caption (block)


          
Credit cards: Visa MasterCard American Express

HTML

Credit cards: Visa MasterCard American Express

output

Fieldset groups related input fields, adds a border; legend supplies a caption

Styling Form Elements


          element[attribute="value"] {
            property: value;
            property: value;
            ...
            property: value;
          }
          

CSS (template)


          input[type="text"] {
            background-color: yellow;
            font-weight: bold;
          }
          

CSS (example)

output

Attribute selector: matches only elements that have a particular attribute value

Useful for controls because many share the same element (input)

One other handy note

A shortcut for document.getElementById

One method we will use a LOT is document.getElementById. It's handy to declare a shortcut to help us out


  function $(id) {
    return document.getElementById(id);
  }

JS

Example:

<input type="button" id="do-the-thing" />

HTML


	let button2 = document.getElementById("dothething");
	let button = $("dothething");               // returns the same as above.

JS

Timers

Used to delay or set intervals for executing functions

Setting a Timer

method description
setTimeout(function, delayMS) arranges to call given function after given delay in ms
setInterval(function, delayMS) arranges to call function repeatedly every delayMS ms
clearTimeout(timerID)
clearInterval(timerID)
stops the given timer

Both setTimeout and setInterval return an ID representing the timer

  • This ID can be passed to clearTimeout/Interval later to stop the timer

setTimeout Example


          
          
          

HTML


          window.onload = function() {
            document.getElementById("clickme").onclick = delayedMessage;
          };

          function delayedMessage() {
            document.getElementById("outputText").innerHTML = "Wait for it...";
            setTimeout(sayBooyah, 5000);
          }

          function sayBooyah() { // called when the timer goes off
            document.getElementById("outputText").innerHTML = "BOOYAH!";
          }
          

JS

output

setInterval Example


          let timer = null; // stores ID of interval timer
          function delayMsg2() {
            if (timer === null) {
              timer = setInterval(mowgli, 1000);
            } else {
              clearInterval(timer);
              timer = null;
            }
          }

          function mowgli() {
            document.getElementById("outputText").innerHTML += "Mowgli!"
          }
          

JS

output

Passing Parameters to Timers


          function delayedMultiply() {
            // 6 and 7 are passed to multiply when timer goes off
            setTimeout(multiply, 2000, 6, 7);
          }

          function multiply(a, b) {
            alert(a * b);
          }
          

JS

Any parameters after the delay are eventually passed to the timer function

  • Doesn't work in IE; must create an intermediate function to pass the parameters

Why not just write this?


          setTimeout(multiply(6 * 7), 2000);
          

JS

Common Timer Errors

Many students mistakenly write () when passing the function


          setTimeout(booyah(), 2000);
          setTimeout(booyah, 2000);

          setTimeout(multiply(num1 * num2), 2000);
          setTimeout(multiply, 2000, num1, num2);
          

JS

What does it actually do if you have the ()?

  • It calls the function immediately, rather than waiting the 2000ms!

The Keyword this


          this.fieldName                 // access field
          this.fieldName = value;        // modify field
          this.functionName(parameters); // call method
          

JS

All JavaScript code actually runs inside of an object

By default, code runs in the global window object (so this === window)

  • All global variables and functions you declare become part of window

The this keyword refers to the current object

Event Handler Binding


          window.onload = function() {
            document.getElementById("textbox").onmouseout = booyah;
          };

          function booyah() { // booyah knows what object it was called on
            this.value = "booyah";
          }
          

JS

output

Event handlers attached unobtrusively are bound to the element

Inside the handler, that element becomes this