Pergunta

I am looking at "HTML" and "JavaScript" and I have a prompt box that asks for the "users name", I was wondering if there's a way of then posting the name they have entered onto the webpage.

To give a bit of background I am creating a game and once the user has entered their name I would like to display it underneath a canvas that contains the game, alongside their score, here is what I have so far.

Code:

var player=prompt("Please enter your name");

if (player!=null)
{
x="Hello " + player + ;
document.getElementById("demo").innerHTML=x;
}
Foi útil?

Solução

Change your opening body tag to this:

<body onload="placeName();">

Then, your JS file should look like this:

function placeName(){
  var name = prompt("Enter name");
  if (name != null){
    var greeting = "Hello " + player + "!";
    document.getElementById("demo").innerHTML = greeting;
  }
}

You also need to make sure that you have a div or something of the sort with the id demo to actually change when the function runs. That's extremely important. The only thing that's different above from what you did is that it waits until the body loads to prompt the user. Your JS file may have loaded before your document, which could cause issues. Also make sure that you have linked your JS file to your HTML file or have put it in script tags in the head. If none of that works, check your console for errors and put it in a JSFiddle so that we can see all of your code to check for errors.

Outras dicas

try this:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x;
    var person = prompt("Please enter your name", "Harry Potter");

    if (person !== null) {
        x = "Hello " + person + "! How are you today?";
        document.getElementById("demo").innerHTML = x;
    }
}
</script>

</body>
</html>

from http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top