prompt(), variables, and if statements


prompt() is an easy way to get information from your website users.

You can use it like this:

<button onclick='prompt("What is your name")'>Ask a question</button>

To get their answer, store it in a variable, like this:

<button onclick='var name = prompt("What is your name"); alert(name + " is a pretty dumb name.")'>Get some name advice</button>

Here, name is a variable that stores whatever your visitor types in. name + " is a pretty dumb name." will add what they typed in (stored in name) to " is a pretty dumb name", so for anything they type in they'll get told their name is pretty dumb.

<script> blocks

This is starting to get complicated to store in the onclick property, so let's move the javascript to its own section just like we did with the <style> tag in the CSS lessons. This code does exactly the same thing as above:

<script>
function getName(){
  var name = prompt("What is your name?");
  alert(name + " is a pretty dumb name.");
}
</script>

<button onclick="getName()">Get some name advice</button>

This is a little more complicated, but now we have more room to do some fun stuff :D

if statements

Let's make it do something different depending on what your user enters:

<script>
function getName(){
  var name = prompt("What is your name?");
  if(name === "Christian"){
    alert("Christian is the best name ever.");
  }else{
    alert(name + " is a pretty dumb name.");
  }
}
</script>

<button onclick="getName()">Get some name advice</button>


Resources


Challenge

Make a website with a riddle that visitors can guess. If they guess correctly, congratulate them. If not, give them a hint.

Bonus points for having a special case if they leave the prompt blank.


Solutions

Try this challenge on your own first, then come back here to see other people's solutions.

Try this challenge on your own first, then come back here to see other people's solutions.