Introduction to JavaScript Spring 2011 Class 6

esse quam videri
Jump to: navigation, search

Back to Introduction to JavaScript Spring 2011


Forms and Get (old school)

Forms are a good way to take user input.

Here's an old school way to get data with forms, then send it to a page that processes the data.

html:

 <form id="myForum" method="get" action="info.html">
 	  name: <input type="text" name="name" />
 	  occupation: <input type="text" name="occupation" /> 
 	  <input name="send" type="submit" value="Send!" />
 </form>

This is a standard html form. When you click on the send button, it's going to load the webpage specified in the form's action attribute. Since the form's method is set to get, it will attach all of the names and values of it's input fields to the URL after it loads info.html

javscript (to be included on info.html):

 function getUrlVars() {
 	  var vars = [], 
 	  	  hash;
 	  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 	  for (var i =0; i < hashes.length; i++){
 		  hash = hashes[i].split('=');
 		  vars.push(hash[0]);
 		  vars[hash[0]] = hash[1];
 	  }
 }
 getUrlVars();
 
 document.write("someone named " + vars.name + " was a " + vars.occupation);

Don't worry about the getURLVars() function. You don't need to know how it works. All you need to know, is it looks for all of the variables and values that were sent from the last page. Then it creates an object called vars. By using vars.name from input field , you can get all of the variables that were sent via the get method.

Document.write is an old school way of writing text/markup to the page. I avoid it whenever possible.

A more modern method

html:

 <form id="myForum">
 	  name: <input type="text" id="userName" />
 	  occupation: <input type="text" id="userOc" />
 	  <input id="sendOutput" type="button" value="Send!" />
 </form>

javascript (included on the same page)

 var subBtn = document.getElementById('sendOutput');
 subBtn.addEventListener('click', formClick);
 
 function formClick(){
 	  var name = document.getElementById('userName').value;
 	  var occ = document.getElementById('userOc').value;
 	  var tn = document.createTextNode("someone named " + name + " was a " + occ);
 	
 	  var para = document.createElement('p');
 	  para.appendChild(tn);
 	  document.body.appendChild(para);
 }

In this example, there is only one page, we're not sending the data to a new page. There is no page refresh either. We attach an event listener to the submit button (which has a type of "button" now). The event listener calls a the formClick() function when the submit button is clicked. The function appends a paragraph with the desired output to the body element.

In class work #2: Madlibs

  • must take in words from the user
  • must concatenate those words into a story
  • must display the story in an html element.