Friday, September 5, 2008

Message input boxes

1. Put the following code in the head of your HTML document.

<script language= “JavaScript”>
<!—

var yourname = prompt('Type your name here');
document.writeln("<center>Welcome, "+ yourname+"</center>");

//-->
</script>



2. Reload the page in your browser window.
3. Type your name.

The browser will type your name in the window, along with the welcome message. These input strings can be used to personalize your web page. Let’s take a closer look at the first line of code.

var yourname = prompt('Type your name here');


This is an example of a variable declaration. As we mentioned, a variable in JavaScript can take on any form, such as integer, character, or string. Just like a person has a name, in order to refer to a variable, you must give it a name. You make a variable with the word var as shown above, and the name is the word immediately following var. So in this case the name of the variable is yourname. The equal sign assigns the variable the value to its right (i.e. 4, 8+5, “c”, “chocolate devil”). The prompt method will get a value for yourname as you saw when you ran the program. We say that the prompt method returns a value, which is stored in the variable yourname. Some methods return values, some don’t.

The line:

document.writeln("<center>Welcome, "+ yourname +"</center>");


looks a lot more complicated than it is. It uses whatever value you have for yourname, which you get from the text prompt window. As you saw, it types on the screen “Welcome,” and then your text. The <center>, </center> tags are familiar looking HTML tags, and indeed, all they do is center your message.