Thursday, September 19, 2013

JavaScript Interactive Message PopUps

 The 3 "commands" involved in creating alert, confirm, and prompt boxes are:


window.alert()

window.confirm()

window.prompt()


Lets look at them in detail. 


  • The first one is:

window.alert()


This command pops up a message box displaying whatever you put in it. For example:


<body>

<script type="text/javascript">

window.alert("My name is George. Welcome!")

</script>

</body>


  • The second one is:

window.confirm()


Confirm is used to confirm a user about certain action, and decide between two choices depending on what the user chooses.


var x=window.confirm("Are you sure you are ok?")

<script type="text/javascript">

if (x)

window.alert("Good!")

else

window.alert("Too bad")

</script>



There are several concepts that are new here, and I'll go over them. First of all, "var x=" is a variable declaration; it declares a variable ("x" in this case) that will store the result of the confirm box. All variables are created this way. x will get the result, namely, "true" or "false". Then we use a "if else" statement to give the script the ability to choose between two paths, depending on this result. If the result is true (the user clicked "ok"), "good" is alerted. If the result is false (the user clicked "cancel"), "Too bad" is alerted instead. (For all those interested, variable x is called a Boolean variable, since it can only contain either a value of "true" or "false").


  • The third one is:

window.prompt()


Prompt is used to allow a user to enter something, and do something with that info:


var y=window.prompt("Enter your name")

<script type="text/javascript">

window.alert(y)

</script>



The concept here is very similar. Store whatever the user typed in the prompt box using y. Then display it.


No comments:

Post a Comment