Jump to content

project


djp1988

Recommended Posts

Hi, I have got the book "JavaScript bible" and at the end of every chapter you must do exercises, and I have to make a page that prompts the visitor to enter their name, and then use JavaScipt to get the answer and insert it into the body welcoming the visitor by his name on screen... but i am stuck can anyone help me out?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>	<title>Test</title><script type="text/javascript">function welcome() {	var answer = prompt("What's your name?","");	if (answer) {		alert("hi " + answer + " !");	}	else {	alert("You are lucky, you can remain anonymous!");	}}window.onload = welcome();</script><script type="text/javascript">function print() {	if (answer) {	document.getElementById("here").inner HTML =	"Welcome to my site, " + answer + " have fun here";	}}window.onload = print();</script></head><body><div><h1>Wicked site !</h1></div><div id="here"></div><p>Excellent content here...</p></body></html>

Link to comment
Share on other sites

The answer is simple. Put this in the head:

<script type="text/javascript">function print(ans) {	document.getElementById("here").inner HTML =	"Welcome to my site, " + ans + ", have fun here";}function welcome() {	var answer = prompt("What's your name?","");	if (answer) {		alert("hi " + answer + " !");		print(answer);	}	else {	alert("You are lucky, you can remain anonymous!");	}}window.onload = welcome();</script>

Link to comment
Share on other sites

The only thing wrong with your original code is that the second function doesn't have access to the answer from the first function. You can get around that by storing the answer in a global variable. A global variable in Javascript is a variable defined with the var keyword outside of any other function scope. So the only change you need is to change this:

function welcome() {	var answer = prompt("What's your name?","");

to this:

var answer;function welcome() {	answer = prompt("What's your name?","");

That way you declare the answer variable as global so that both functions (the welcome and print functions) have access to the same thing.Also, you might want to rename your print function to something else. There's already a function called window.print that you use to print the page. Defining a new function in the global scope called print might try to override that function, it would be better to use a different name for your function.Also, this line has an error:document.getElementById("here").inner HTML =There's no space between "inner" and "HTML".

function print() {	if (answer) {	document.getElementById("here").innerHTML =  "Welcome to my site, " + answer + " have fun here";	}}

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...