Wednesday, December 30, 2009

Opening a URL from a Select Form


This gets the value associated with the selected text (a URL) and opens the web document. Some details follow below.

First the HTML code for this:
<script type="text/javascript">
function openURL() {
 var selectionIndex = document.forms.urlChoose.elements["theURL"];
 var myURL = selectionIndex.options[selectionIndex.selectedIndex].value;
  document.location.href=myURL;
  return true;
}
</script>

<form action="" name="urlChoose">
<select gtbfieldid="23" name="theURL">
   <option selected="selected">Choose a Website</option>
   <option value='http://www.scriptsforapple.com/'>AppleScript Site</option>
<option value='http://read-and-write-german-language.blogspot.com/'>German Site</option>
<option value='http://editing-web-color-html.blogspot.com/2009/12/box-style-properties.html'>Color HTML Site</option>
</select>

<input name="submitURL" onclick="openURL()" type="button" value="Go to site" />
</form>


When a choice is selected and the button is clicked, 'onclick' sends a call for the 'openURL' function in the JavaScript (script) section.

The variable var selectionIndex is assigned a value of document.forms.urlChoose.elements["theURL"] . This gives it the value of the element named 'theURL' which is a URL of derived from the form named 'urlChoose' of the current document.

Next, the variable 'myURL' gets the value (a URL) of the index number 'selectionIndex' of 'selectionIndex' and opens the appropriate website.


Digg 'Learning How to Write JavaScript Code'!


Here what is shown on the page:






Please leave me a comment on this site.

For a look at using color with HTML go to: http://editing-web-color-html.blogspot.com/

Wednesday, December 9, 2009

Getting Value of Element from a Select Form

Apple-II-Shipping
This gets the value of the selected text and displays it in an alert box. This can be a little confusing (only a little), so some details follow below.

First the HTML code for this:
 
<script type="text/javascript">
function displayLanguage() {
 var selectFromForm = document.forms.languageChoice.
elements["language"];
 var myValue = selectFromForm.options[selectFromForm.
selectedIndex].value;
  alert('Your native language is \"'+ myValue +"\"");
  return true;
}
</script>

<form action="" name="languageChoice">
<select getFieldId="23" name="language">
   <option selected="selected">Select language<
/option>
   <option>English</option>
   <option>French</option>
   <option>Spanish</option>
   <option>German</option>
   <option>Italian</option>
</select>
<input name="executeButton" onclick="displayLanguage()"
 type="button" value="Language" />
</form>

Keep in mind that to understand this, first focus on the form block of the HTML which gathers the data that will be used by the JavaScript block.

With that said, when a choice (English,French ..whatever) is selected and the button is clicked, 'onclick' sends a call for the 'displayLanguage' function to the corresponding script.

The variable var selectFromForm is assigned a value of document.forms.languageChoice.elements["language"] . This gives it the value of the element named 'language' of the form named 'languageChoice' of the current web document.

Next, the variable 'myValue' gets the value (text) of the index number 'selectedIndex' of 'selectFromForm' and then, finally displays it in an alert box.

Look below and this should be fairly clear.

Note: You may have noticed above, that the logic of the variable assigned reads from right to left.

What is shown on the page:


 
Digg 'Learning How to Write JavaScript Code'!


Please leave me a comment on this site.

For a look at using color with HTML go to: http://editing-web-color-html.blogspot.com/

Sunday, November 15, 2009

The For Loop and For...In Loop


Sometimes you need to execute code repeatedly for a given number of times. The For Loop and For...In Loop structures accomplish this. These are similar to AppleScript's Repeat and Repeat In structures.

<html>
<body>
<script language=javascript>

var degreesFahrenheit = new Array (212, 32, -459.15);
var degreesCelsius = new Array ();
var repeatCount;

for (repeatCount = 0; repeatCount <= 2; repeatCount++)
{
degreeCelsius [repeatCount] = 5/9 * (degreeFahrenheit [repeatCount] - 32)
}

for (repeatCount = 2; repeatCount >= 0; repeatCount--)
{
document.write ("Value " + repeatCount + " was " + degreeFahrenheit [repeatCount] + " degrees Fahrenheit");
document.write (" which is " + degreeCelsius [repeatCount] + " degrees Celsius<br>");
}

</script>

</body>
</html>



This statement sets the parameters for the loop. The parameters are separated by a semicolon:

for (repeatCount = 0; repeatCount <= 2; repeatCount++)


The first two parameters, repeatCount = 0; repeatCount <= 2;
, set the loop count to start at 0 and end at 2.


The last parameter, repeatCount++
, increments the loop by 1 each time it loops through. As you might have surmised, repeatCount--
would increment the loop by 1 each time from from a higher initial value such as 3.

The For...In loop is used mainly with arrays. It makes it possible to loop through arrays without needing to know ahead of time how many elements are contained in the array.

Example:


var textItemArray = new Array("Books", "Magazines","Newspapers");
var theTextItem
for (theTextItem in textItemArray)
{
alert(textItemArray [theTextItem])
}



This loops through the elements in textItemArray
and displays an alert containing each.

Learning How to Write JavaScript Code' to Technorati Favorites



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

Monday, October 26, 2009

Using the Switch Statement


The Switch Statement is a sort of Conditional, it tests for instances of something, usually a variable value.

 


Here the function displayAlert assigns a value to the variable OSName by way of a prompt box:
 

Edit code, then select and copy:  
Command-A/command-C to copy (Mac) | alt-A/alt-C (Windows)

Here the function displayAlert is called by clicking on an image in the main body of the page:
 
<a href="http://www.yourDomain.com/" onclick="displayAlert()"><img src="http://www.yourDomain.com/yourImage.jpg"/></a> </body> </html>

Or you could create a button, 'Switch Activate' in this case, to do the job:

<button type="button" name="Switch Activate" onclick="displayAlert()"></button>
 

Want HTML Code? Go to: http://write-html-code.blogspot.com/
 
Learning How to Write JavaScript Code' to Technorati Favorites

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/

Saturday, August 15, 2009

JavaScript Prompt Box


These are used when you want the user to enter text into a dialog box. They are like AppleScript dialogs with 'default answer...' They display "OK" and "Cancel" buttons and a text entry box. "OK" returns the text that was entered. "Cancel" returns the value null. The null value is somewhat like the empty value in AppleScript:


<head>
<script type="text/javascript">
function screenNamePrompt()
{
var screenName=prompt("Enter your screen name","MacUser");
if (screenName!=null && screenName!="")
  {
  alert("Your screen name is " + screenName + " !");
}
else
alert("Don't you have a screen name?");
}
</script>
</head>


The Statement 'var screenName=prompt("Enter your screen name:","MacUser");' tells JavaScript that you are requesting a dialog with the text prompt: 'Enter your screen name:' and the default entry text 'MacUser'

There are a few things to note here. First, the line 'if (screenName!=null && screenName!="")':

The symbol
'!' means not or not equal to. So, in this case, if the user clicks the cancel button or enters no text at all, the first conditional statement is executed: 'alert("Your screen name is " + screenName + " !");'

The next thing concerns what is referred to as concatenation or parsing (putting two or more strings of text together as one).

The previous statement:
'alert("Your screen name is " + screenName + " !");' uses the plus sign to put strings together as one. In AppleScript, we would use the ampersand '&'



<input type="button" onclick="screenNamePrompt()" value="Prompt Screen Name" />


Click on this button to see prompt dialog:




If you have questions or would like to suggest a post, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter




Friday, May 8, 2009

JavaScript Confirm Box Dialog



The confirm box, has a syntax that is similar to that of alerts. It is often used when you want ask the user to make a decision on something. It has an "OK" and a "Cancel" button.

If the user clicks "OK", the value returned is true. If the user clicks "Cancel", false is returned. These boolean values can be used for further script execution. Once again, they are usually placed either within the <head> tag or the <body> tag as is the case here. It is not required, but is good style as it makes the page flow efficiently and gives it a professional look :


<head>
<script type="text/javascript">
function userConfirm()
{
var response=confirm("Press a button");
if (response==true)
{
document.write("OK button!");
}
else
{
document.write("Cancel button!");
}
}
</script>
</head>


Note here that in 'var response=confirm("Press a button");' above, we use an equal sign to assign a value to the variable 'response'. Note in the next line that 'if (response==true)' uses double equal signs to indicate equals and also unlike AppleScript the word 'then' is omitted.

'document.write("OK button!");' tells the function to write "You pressed OK!" to the web page (or blog). The text string must be enclosed by quotes and parenthesis.




<body>
<input type="button" onclick="userConfirm()" value="Display confirm dialog" />
</body>


This is very similar to the alert syntax and should be easy to understand.




The button above would show this dialog:

confirmAlert


If you have questions or would like to suggest a post, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter

What is this??

Tuesday, April 14, 2009

JavaScript and Simple Interaction with the User




Alert Boxes (dialogs) are similar to AppleScript dialogs in that they communicate the state of something to the user. While AppleScript dialogs can be used in web pages as well as on the desktop, JavaScript dialogs are used almost exclusively for the internet.

In this, the first post on this topic, I will use the various types of JavaScript 'Boxes' to illustrate some of the basics of the JavaScript syntax.

Although you can call for an external JavaScript, they are most commonly placed within either the
<head>
tag or the <body>
tag of an HTML page:


<head>
<script type="text/javascript">
function userAlert()
{
alert("Welcome to my web page");
}
</script>
</head>





When you place a function, in this case an alert dialog, within the head tag, it 'preloads' the function when the page is displayed so that when it is needed there is no delay. You must begin with the statement '<script type="text/javascript">'
, which tells your computer to expect something with the JavaScript syntax.

Next, the name of the function (case sensitive, ie: userAlert() and useralert() are not the same and could be two totally different functions).

Then the statements, each line ending with ';' and an entire block of statements enclosed by '{}' Note that in a single statement block such as the one above the so-called 'curly brackets are optional'.

In the body section of the page:

<body>
<input type="button" onclick="userAlert()" value="Display alert" />
</body>


Click the button below to see the dialog



input type="button"
says to display a button on the page and value="Display alert"
says that the button will bear the name "Display alert".

Lastly,
onclick="userAlert()"
tells JavaScript that when the button is clicked, to execute what is in the preloaded function 'userAlert'.



If you have questions or would like to suggest a post on another JavaScript issue, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter