Tuesday, September 22, 2009

Dealing with Error Messages with Try...Catch


Sometimes you want to give the user some feedback based on information that they have entered. If they have entered something that does not fit with the information requested, you want to be able to tell them so that they will understand what course of action to take.

The syntax of the 'Try...Catch' pair of JavaScript will look fairly familiar to you if you are familiar with 'try...on error' used in AppleScript. It has the same purpose.

So, let's examine this script and see how it works:


<script type="text/javascript">
function ageMessage()
{
var ageInteger=prompt("Please enter your age:","16");
try
{
if(ageInteger<0)
{
throw "errorCase1";
}
else if(ageInteger<16)
{
throw "errorCase2";
}
else if(ageInteger>16)
{
throw "errorCase3";
}
else if(isNaN(ageInteger))
{
throw "errorCase4";
}
}
catch(error)
{
if(error=="errorCase1")
{
alert("This is someone who has not even been born yet!");
}
if(error=="errorCase2")
{
alert("You must be at least 16 years old to apply for a driver's license in this state! Sorry.");
}
if(error=="errorCase3")
{
alert("Please come in and register with us to apply or revalidate your driver's license.");
}
if(error=="errorCase4")
{
alert("Invalid entry! You must enter an age here!");
}
}
}
</script>
<input type="button" value="Reply Prompt" onclick="ageMessage()" />



License bureau's records division to determine if the user is of legal age to apply or revalidate a current driver's license. The default is 16 (the legal age in most US states to acquire a license)

var ageInteger=prompt("Please enter your age:","16");
The prompt that sets the variable 'ageInteger' that will be evaluated.

The 'try' segment evaluates the variable var 'ageInteger'

If the variable value meets a particular value, then it is assigned a 'throw' or case value that is sent on to the 'catch' (error) subroutine, which will respond with some feedback.

Try this out to see how this can be put to use in one of your pages:







Learning How to Write JavaScript Code' to Technorati Favorites

Want HTML Code? Go to: http://write-html-code.blogspot.com/


Friday, September 11, 2009

JavaScript to Open URL in New Window



Sometimes you want to confirm an action before it is carried out. This script displays a confirmation box and, if confirmed, opens the specified URL:


<script type="text/javascript">
function userConfirm()
{
var response=confirm("Do you want to go to the Home page?");
if (response==true)
{
window.open("http://www.yourURL.com/")
}
else
{
alert("User Cancelled!");
}
}
</script>


<a href="http://www.yourURL.com/" onclick="userConfirm()"><img src="http://www.yourURL.com/wp-content/uploads/2009/06/yourImg.jpg" alt="Image Name" title="Image Name" width="115" height="80" class="alignright size-full wp-image-520" /></a>


Click on the graphic below to see how this works:



Image Name

Want HTML Code? Go to: http://write-html-code.blogspot.com/