Monday, 4 April 2011

JavaScript: popup boxes

   


Today we are going to play with popup boxes and JavaScript!
What we are going to do is very simple. First of all we will create the code for a button that will trigger a simple alert box. Then we are going to create a confirm box and a prompt box.

The alert box
The JavaScript syntax used to make an alert box is:
alert("text");
The code itself is very simple and will pop up an alert box with an "ok" button. In order to close the box, the user needs to click the "ok" button.
The following is a good example:




The code behind it is:
<script type="text/javascript">
function open_alert()
{
alert("Hello! Welcome to The Web Thought!");
}
</script>
<input onclick="open_alert()" type="button" value="Click me!" />
The onclick event will call a funtion (open_alert) that will actually use the alert command to make the alert box pop up. As you can see it is more difficult to explain than to implement.

The confirm box
If the alert box has only an "ok" button, the confirm box has an "ok" button and a "cancel" button. It is mainly used to - guess what - confirm something. If the user clicks "ok" the box returns "true", if the user clicks "cancel" the box returns "false".
The basic syntax is:
confirm("text");
Let's see it in action:



Again the code behind it is:
<script type="text/javascript">
function open_confirm()
{
var r=confirm("Choose between ok or cancel");
if (r==true)
  {
  alert("OK!");
  }
else
  {
  alert("Cancel!");
  }
}
</script>
<input onclick="open_confirm()" type="button" value="Click me!" />
In this case, we assign a variable r as value returned by the confirm command. We then check for the returned value: if it's true or false.

The prompt box
Last but not least, the prompt box which will ask the user to fill in a box (prompt). The command will return the input value if the user clicks "ok", or null if the user clicks "cancel".
First of all, the syntax:
prompt("text","defaultvalue");
The text is just the text inside the pop up, while the defaultvalue is the default value inside the input box.



The code is very simple:
<script type="text/javascript">
function show_prompt()
{
var name=prompt("What's your name?","Denny Crane");
if (name!=null && name!="")
  {
  alert("Hello " + name + "!");
  }
}
</script>
<input onclick="show_prompt()" type="button" value="Click me!" />

Please share your thoughts about it!

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.