iEntry 10th Anniversary CSS Snippets JavaScript Snippets

 
 





Prompts and Alerts

There are times when you may need some interaction with the user. You may want to personalize a greeting for them when they enter your site. You can do all of these with the prompt function in JavaScript, this is just one of three different alerts that you can use in JavaScript.

<script language="JavaScript" type="text/javascript">
  name=prompt("Please enter your name");
</script>

This will create an alert message that will allow the user to type in their name. You can then use this to customize the site by having their name where ever you want to use it.



What if you want a user to confirm some information? You can use the confirm function.

<script language="JavaScript" type="text/javascript">
  confirm("Are you for sure you want to continue?");
</script>

The confirm function will allow the user to answer yes (ok) or no (cancel), and return a true or false value. You can use this in a script to have the user confirm if they want to continue with the action they are about to do or if they want to stop.



The last type of alert, is the a basic alert. This just tells the user something you want to bring to their attention.

<script language="JavaScript" type="text/javascript">
  alert("Welcome to Code-Sucks.com");
</script>

This alert will just pop up a box that would read "Welcome to Code-Sucks.com", and the user can click Ok to close the box.



If we were to put all of these together we could create a customized greeting that will allow the user to input their name, confirm that it is correct, and give them an alert that welcomes them to the site.

<script language="JavaScript" type="text/javascript">
function greetings(){
 
 name = prompt("Please Enter Your Name.");

 if (name){
   if(confirm("Is "+name+" really your name")){ 
    alert("Welcome "+name+ "to Code-Sucks.com)
   }else{
    alert("Welcome to Code-Sucks.com")
   }
 }else{
   alert("Welcome to Code-Sucks.com")
 }
}
</script>

So what we have done was set the users input from the prompt message to the variable name. Since we want to greet the user even if they do not put in their name, we use a if else statement. If the user does not enter information in the prompt, or cancels the prompt, then we give a generic message that just welcomes the user. If they do enter any information, we then want to confirm, that this information is correct. We do this with the confirm function. Depending on what the user chooses, we either greet them with a personalized message or give them a generic message.