Java Reference
In-Depth Information
And last of all we'll need a js folder that contains a file called scripts.js. In this file, let's
start off by assigning the form to a variable and then adding an event listener for when the
form is submitted:
var form = document.forms.hero;
form.addEventListener("submit", makeHero, false);
The event listener will call the
makeHero()
function when the form is submitted. In this
function, we want to create an object from the information provided in the form. Let's im-
plement that function by adding this code to scripts.js:
function makeHero(event) {
event.preventDefault(); // prevent the form from being
submitted
var hero = {}; // create an empty object
hero.name = form.name.value; // create a name property
based on
↵
the input field's value
alert(JSON.stringify(hero)); // convert object to JSON
string and
↵
display in alert dialog
}
This function uses the
event.preventDefault()
method to stop the form from be-
ing submitted. We then create a local variable called
hero
and assign it to an empty object
literal. We'll then augment this object with properties from the form, although we only have
the
name
property at the moment. Once the
hero
object is created, it could be returned by
the function and then used in the rest of the program. Since this is just for demonstration
purposes, we simple use the
JSON.stringify()
method to convert the
hero
object
into a JSON string and then display it in an alert dialog.
Open up hero.htm in a browser and enter the name of a superhero and you should see a
screenshot similar to
Figure 8.4
.
