Now that we know how to use variables and strings, we need to look at input from someone on our page. To do this we use the prompt function. In this case we will look at making a short and very simple mad lib. The first thing we need to do is to set our basic head statements for JavaScript and declare some variables. These will be used from the above example.
<HTML> <HEAD> <TITLE>Untitled</TITLE> <Script Language="JavaScript"> <!--Hide me from the dumb browsers
/* here is my variable declaration section */
var sec_per_min=60; var min_per_hour=60; var hours_per_day=24; var days_per_year=365;
/* here is my formula section for my variables */
var sec_per_day=sec_per_min*min_per_hour*hours_per_day; var sec_per_year=sec_per_day*days_per_year;
Next I will need to set some prompts to get information from the user. Prompts are variables that prompt the user for the value that is to be assigned to the variable. They all follow the form of - var something=prompt("Whatever my question or request for input is.");. In the code below you will notice that there is a comma after the initial prompt question, followed by another word(s) in quotations. This is used to set the default value in the prompt window. This is entirely optional and not required for the prompt to work. I have also added a variable declaring that alive is equal to someone’s age times the number of seconds in a year.
/* here are my prompts for names and ages */
var name=prompt("What is your name?","Name"); var age=prompt("How old are you?","Age"); var mood=prompt("Are you happy or sad?","happy or sad"); var alive=sec_per_year*age;
Finally I use the document.writeln to send some output to my HTML page. Note that values for variables are not placed in quotes, and strict text in between the variables is placed in quotes. You should also note how I have separated variables and text in the third line.
/* here is how I can write some output to my HTML page */
document.writeln(name); document.writeln(" has been alive for "); document.writeln(alive," seconds is very ",mood," right now!");
// stop hiding me --> </script>
</HEAD>
Why don’t you give this a try and see how it works? Now lets say that I want to play with some formatting. To do this we would simply use some formatting functions like those below. In this case. In order to speed things up a bit, I have also added the following variable to the head section of my script.
var sentence=name+" has been alive for "+alive +" seconds and is very "+mood+" right now!";
With this simple script I have told the browser to write the sentence 4 times, each time on a separate line, and converting the sentence to bold, Upper Case, and the color red! Give it a try!