You Are Here: Home »Tutorials»Html_js »   Alert confirm prompt Tuesday February 9th 2010

Alert, Confirm And Prompt Boxes

These are three of the most basic functions that Javascript can perform, and although many people consider them annoying there's a large number of things they can be used for, so i thought i'd quickly run through how they work.

Alert Boxes

You've probally seen one at somepoint that says "welcome to my site" or something similar, well if you want to use this type of popup to greet people when they enter a page, the code is very simple.

<script type="text/javascript">
<!--
alert ('Your message here!')
//-->
</script>

That's it, and you can make use of those when a page loads, in a function, on a certain event, after a certain time has elapsed or in other ways.

Just incase you're still confused

Confirm Boxes

Confirm boxes are similar to a simple popup alert except they let you give people two options, instead of just making a statement or giving a message.

Need an example?

Ok so how to go about creating creating a confirm box?

<script type="text/javascript">
<!--
var msg = confirm ('Question here')
if(msg)
   alert ('message if they clicked ok')
else
   alert ('message if they clicked cancel')
//-->
</script>

Quite simple to understand i think. The variable that we set, which in this case is named 'msg' can be called anything, 'answer' is probally the most logical, but it doesn't really matter.

Prompt Boxes

Finally prompt boxes which are basically moving on one stage further as they require the user to enter information which will be used in the final output rather than it being something that's pre-defined.

First the example

I'm sure you can think of some interesting stuff to do with that, and once again the code is very simple.

<script type="text/javascript">
<!--
var name = prompt ('What\'s your name?','')
alert ('Hi ' + name)
//-->
</script>

So it's two simple parts, first we define variable (var) to represent whatever the user put into the box, i called it name but you can call it anything, then in the second part we make use of that variable.

I used an alert box to popup the name just as an example, there's other ways you could do that, for instance if you wanted to print the message to the page you could use the following instead:

document.write('Hi ' + name)

That's about it, simple stuff eh?