Goodies to Go (tm)
November 4, 2002-- Newsletter #205

By Vince Barnes



Goodies to Go (tm)
November 4, 2002--Newsletter #205

This newsletter is part of the internet.com network.
http://www.internet.com
 


Featured this week:

* Goodies Thoughts  - Validating an SSN
                                  or Similar Numbers.
* Q & A Goodies
* News Goodies
* Feedback Goodies  
* And Remember This...

 


 

Goodies Announcement

Just in case you missed it before, the new Beyond HTML Goodies book is now available!

 

Go beyond the basics and learn how the pros add and use dynamic HTML features and advanced JavaScript techniques. Beyond HTML Goodies demonstrates dozens of new and different features readers can add to their existing Web pages using HTML and JavaScript. The book starts with simple text and image tips, such as adding a clock to a Web page or causing text to appear when the mouse moves over an image. It gradually builds to more complex tricks, including manipulating forms or working with cookies behind the scenes. Throughout the book, readers enjoy Joe's snappy style and "to the point" discussion of each "goody" in the book.

 

http://books.internet.com/books/0789727803

 

 

Goodies Thoughts - Validating an SSN or Similar Numbers.

This question crops up every now and then. How do you validate a Social Security Number (or other such number with special formatting)? There are as many solutions to a given problem as there are creative minds applied to the task of resolving it. I thought it would help to show a couple of fairly simple JavaScript solutions that perform some basic validation. Ultimately, if you have the need to be certain of the validity of an entered SSN you would need to verify it against a database. This would be a more involved solution than we could describe here in the newsletter. What we can do is to show techniques for validating that only certain characters are entered into a field and to look for a particular type of formatting. A US Social Security Number follows the format 999-99-9999 (three digits, hyphen, two digits, hyphen, four digits.) If you need to get the basics of JavaScript, see this primer:
http://www.htmlgoodies.com/primers/jsp/

In each of these examples, the function is named "regular" and can be called thus:

<INPUT TYPE="TEXT" SIZE="12" MAXLENGTH="12"
onChange="if (!regular(this.value)) alert('Not Valid')">

We use "onChange" to trigger our test when the contents of the field have been changed. We call the "regular" function passing it the value of our input field as a string ("this.value"). We say that if "regular" does not return true ("!" is for "not") put up an alert with the text "Not Valid":
if (!regular(this.value)) alert('Not Valid')

Here is a piece of JavaScript that will check that only certain characters have been entered in a field:

<SCRIPT LANGUAGE="JavaScript"><!--
function regular(string) {
if (!string) return false;
var Chars = "0123456789-";

for (var i = 0; i < string.length; i++)
{ if (Chars.indexOf(string.charAt(i)) == -1)
return false;
}
return true;
}
//--></SCRIPT>

Let's look under the hood.

First we check to see that a string has been passed to our routine and return with an error if not:
if (!string) return false;

Now we define a variable containing each of the characters we allow in the subject field:
var Chars = "0123456789-";

Using a "for" loop, we check each character to see if it is one of the characters in our allowed set. The parameters of the "for" initialize a variable to zero (which we'll use as an index to the characters in our subject field); check to see if the variable is less that the length of our subject field, continuing with the looped code if it is and dropping out (to the instruction following the closing curly-brace) if it is not; and increment our index variable by one:
for (var i = 0; i < string.length; i++)

The test in our "for" loop checks our current character position "string.charAt(i)" to see if it is contained in our permitted set. Using the "indexOf" method of our allowable characters variable "Chars" causes the JavaScript to scan along the field for a matching character. When there is a match, "indexOf" gives a value representing the character's position -- for example, if the character was a 2, "indexOf" gives a value of 3 because 2 is the third character in our set. If there is no matching character, "indexOf" gives a value of -1 indicating "not found". If this "not found" error condition occurs, we drop out of our function with a "false" return:
{ if (Chars.indexOf(string.charAt(i)) == -1)
return false;
}

When we have tested all the characters in our input string ("i" is no longer less than "string.length") and we have not yet dropped out of our function with an error ("return false;") we have passed the test and our input contains only characters that are members of our permitted set. We now return indicating that all is well:
return true;

This example, which requires JavaScript 1.2, uses a "regular expression" to compare each character position of the input field to a permitted range:

<SCRIPT LANGUAGE="JavaScript1.2"><!--
function regular(string) {
if (string.search(/^[0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9][0-9][0-9]$/) != -1)
return true;
else
return false;
}
//--></SCRIPT>

Regular Expressions can get complicated to understand and use until you get to know them well. For now, you could use this example as a model. The "search" method checks each character position of "string" to a defined range. "[0-9]" allows that position to be a numeric character in the range zero through nine. "\-" allows the literal character hyphen. "$/" ends the permitted string to make sure there are no more characters. Note that if the input string is too short, a null would not meet the criterion for one of the positions and would cause an error. When there is no failure of the test ("!= -1") we return true, else we return with an error condition ("false")

I hope these explanations give you a little insight into the working of JavaScript as well as providing you with a model for some field validation you might need.
 


Thanks for Reading!
- Vince Barnes

Top

Q & A Goodies

Questions are taken from submissions to our Community Mentors. You can ask a Mentor a question by going to http://www.htmlgoodies.com/mentors/.



Q. I am experimenting with different page layouts with tables. none of the width="" commands in <table> or <td> seem to actually provide the restrictions I am looking for. What am I doing wrong?

A. Table cells expand with their content. Size images the width you want the table cell they are in and use wrap or nowrap on text in the cells. Use <br> on the text to break the line so the cell will be narrower.
[For more about tables, see: http://www.htmlgoodies.com/tutors/tbl.html -- Ed.]




Q. I have a slide show that displays a random picture every 20 seconds. It reloads to display a new picture with the code:
<META HTTP-EQUIV="REFRESH" CONTENT="20;URL=page.htm">
The page automatically refreshes the image every 20 seconds. I have a key press command such that if the viewer presses 'N' it reloads and displays the next image instead of waiting for the full 20 seconds to lapse. I would also like to do the opposite and allow the viewer to pause the slideshow if they wish to view the current image for longer than 20 seconds. Is there a command that will pause the refresh countdown? How can I implement this? I want the pause to be indefinite, so that when the viewer is ready to move on they press the 'N' key for the next image and the countdown to 20 begins again.

A. Below is an example of one way you can do it using the setTimeout() and clearTimeout() functions. I modified this from a Manual Slide Show script I had.
<html> <head> <title>Image and Link Slide Show</title>
<SCRIPT LANGUAGE="JavaScript">
var a=0
// Enter your images Here along with the directory if need be.
var imgs=new Array()
imgs[0]="owls3.jpg"
imgs[1]="hawks2.jpg"
imgs[2]="pic221.jpg"
imgs[3]="eagle1.jpg"
// Array used for preloading
var myimages=new Array()
// Do the preload
for(i=0;i<imgs.length;i++)
{
myimages[i]=new Image()
myimages[i].src=imgs[a]
}
// Enter your URLS and what you want to go in the ALT property.
// This is so when they mouse over the image,
// there will be a small description of the Image or URL.
// Make sure you separate them with an ampersand "&" so that
// the script can separate them out before writing out the link.
var urls=new Array()
urls[0]="http://www.requestcode.com&Requestcode"
urls[1]="http://www.javascriptkit.com&Javascriptkit"
urls[2]="http://www.dynamicdrive.com&Dynamic Drive"
urls[3]="http://www.htmlgoodies.com&HTML Goodies"

// This is the function that displays the images and links.
// You should not have to modify it.
function Doimglink()
{
if(a>imgs.length-1)
{a=0}
if(a<0)
{a=imgs.length-1}
newurls=urls[a].split("&")
if(document.layers)
{
document.mydiv.document.write("<A HREF='"+newurls[0]+"'><IMG
SRC='"+imgs[a]+"' BORDER='0' ALT='"+newurls[1]+"'></A>")
document.mydiv.document.close()
}
if(document.getElementById)
{
elm=document.getElementById("mydiv")
elm.innerHTML="<A HREF='"+newurls[0]+"'><IMG SRC='"+imgs[a]+"'
BORDER='0' TITLE='"+newurls[1]+"'></A>"
}
}
// function used to display random image
function rannum()
{
len=imgs.length // how many entries in the array
prev=a // Save the previous image index
a=Math.round(Math.random()*(len-1))
// If the current image equals the previous image.
// add one to get a different image.
if(a==prev)
{a++}
Doimglink()
Timer=setTimeout('rannum()',3000)
}
// In the DIV below you may have to add the top and left properties
// to the style tag to position it correctly in the window.
// You must keep it positions as absolute for it to work in NS4.0+ browsers.
</SCRIPT>
</head>
<body onLoad="rannum()">
<DIV ID='mydiv' STYLE="position:absolute;top:120;left:200"></DIV>
<DIV ID='ctrldiv' STYLE="position:absolute;top:120;left:100">
<A HREF="javascript:clearTimeout(Timer)">Stop</A> <BR>
<A HREF="javascript:rannum()">Restart</A>
</DIV>
</body>
</html>




Q. A user types their username and password into two different textboxes. When they click the login/submit button it sends them to another page like this:
ftp://username:password@68.34.144.34:21/Members.html
where "username" and "password" is the text they typed in the textboxes. How do I send the information they entered?

A. You can pass them as variables through a JavaScript. Try this tutorial:
http://htmlgoodies.earthweb.com/beyond/jspass.html



Q. I want to create a pop-up window and inside it I want to have a print and close option. What code should I use?

A. The close link code is:
<a href="javascript:self.close();">close window</a>
Print is:
<a href="javascript:self.print();">print</a>




Q. I am using anchor hypertext links <a href>, but they appear to automatically underline the text to be used as the link. Is there any command that will omit the underlining of the text?

A. Use CSS. You can have a linked stylesheet, a piece of CSS inside style tags, or a style attribute in each link. The code you need is text-decoration: none.

<style>
a {text-decoration: none}
</style>
<a href="wherever" style="text-decoration: none">link</a>

[For more about Cascading Style Sheets, see: http://www.htmlgoodies.com/beyond/css.html -- Ed.]




Q. I saw a script that reveals the source code of any web page (http://www.htmlgoodies.com/JSBook/seesource.html ) in a pop-up window. Is there any way to make the source code appear inside a textarea or some other part of an HTML form?

A.
Unfortunately that won't work to place the source in a textarea.
The only way that I know of would be to place it directly in the textarea like the example below.
<html>
<head>
<title>View Source in a Text Area</title>
<SCRIPT LANGUAGE="JavaScript">
function viewsrc()
{
document.vsrc.pgsrc.value="view-source:" +window.location.href
}
</SCRIPT>
</head>
<body>
<CENTER>
<FORM NAME="vsrc">
<TEXTAREA NAME="pgsrc" COLS="70" ROWS="20">
<HTML>
<HEAD>
<TITLE>My source</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function myalert()
{
alert("Hi")
}
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript:myalert()">Click Here</A>
</BODY>
</HTML>
</TEXTAREA>
</FORM>
</CENTER>
</body>
</html>
 

 


*** Mentor Spotlight ***
 

 Jim Young

At HTML Goodies we wish to express our sincere gratitude to our mentors.
All the time our mentor spend reading, researching and answering questions sent in to our Mentor Community is provided voluntarily by our mentors. On occasions, we like to throw a spotlight on a mentor so that you can get to know more about them and so that we can all show our appreciation.
Jim Young is one of our JavaScript Mentors. A lot of our readers receive the benefit of Jim's expertise each week when they send in their JavaScript questions. Many editions of this newsletter have carried examples of his work. Says Jim:
"I am a Senior Programmer Analyst at a hospital in Michigan. I have over 15 years experience in Information Systems. Most of my experience has been on Mainframe applications. The last few years I have concentrated on learning HTML, JavaScript and Website Design in general. I am have added Perl and Java to expand my knowledge and job skills."
 

 

 

Top

News Goodies


Intel Serves Up its Next Gen Xeon MP
[November 4, 2002] OEMs and partners fall in line as the chip making giant addresses upcoming 16 and 32 way boxes with a 2GHz processor, code named 'Gallatin.'

Click here to read the article



Judge Approves Microsoft Antitrust Settlement
[November 1, 2002] UPDATE: A federal judge approves the settlement agreement Microsoft reached with the Department of Justice last year.

Click here to read the article



IRS Signs Deal for Free E-Filing
[November 1, 2002] Tax preparers agree to boost percentage of free online tax filings in exchange for promotion on IRS website.

Click here to read the article
 



Today's Portal Could Be Tomorrow's Porn
[November 1, 2002] Domain name expiration problems have factored into some 1,500 mainstream Web sites becoming porn sites, according to research from Websense.

Click here to read the article




Yahoo Goes PHP in Open Source Embrace
[October 30, 2002] The mega portal continues to dance with open-source software with its decision to switch from proprietary languages to PHP for its backend scripting.

Click here to read the article

 

 


Top

Feedback Goodies



Did you ever wish your newsletter was an easy two way communications medium? Ploof! It now is!
If you would like to comment on the newsletter or expand/improve on something you have seen in here, you can now send your input to:

mailto:nlfeedback@htmlgoodies.com


We already receive a lot of email every day. This address will help us sort out those relating specifically to this newsletter from all the rest. When you send email to this address it may wind up being included in this section of the newsletter, to be shared with your fellow readers.


We received lots of email this week indicating the number of typos and other errors in last week's newsletter. A couple of things happened last week: we included peoples questions and answers as asked and answered without editing them. These questions (and sometimes the answers) frequently contain a lot of errors. Sometimes it's difficult to tell a typo in the question apart from the error that is the cause of the problem. An example is the Q&A here:
Q. WHEN I PUT IN <IMG SCR="LITTLECAT_WILDLIFE.GIF"> A PICTURE DOES NOT
DISPLAY, JUST A BOX WITH SOMESORT OF SHAPE THING. CAN YOU TELL ME WHAT I AM
DOING WRONG? WHY MY PICTURE IS NOT BEING DISPLAYED?
A. <img src="dada.jpg"> not <img scr="dada.jpg">
If we correct the typo in the question ("IMG SCR") we also correct the cause of his error. This is a very obvious example, most are more subtle. So we thought that maybe we should just include these Q&A items without editing them. It seems to be a fairly unpopular idea. Perhaps we should edit those items that overtly offend the English sensibilities, leaving the lesser errors alone. (BTW, several responders seem to have missed the point of this correction in Jim's reply.)


I said a couple of things happened -- the other was my bad! I cut and pasted from an interim copy into the live newsletter instead of from the final. To those who pointed out the "there own way" instead of "their own way", I'd like you all to know that this is number one on my list of pet peeves, and all I can say is "guilty as charged!"  I noticed it only moments after it went out and was instantly mortified!  My favorite comment came from the writer who concluded "... and it would do you well to have somebody check it for grammer."  That really is their turn of phrase and their spelling of "grammar"!  A close second indicates "Spelling and obvious grammattical errors"!  It just goes to show that we all can be guilty of this type of keyboard mishap, no matter how hard we try!  At Goodies To Go we will try very hard to eliminate our errers and smelling mistakes! <G>

 

Top
And Remember This . . .


On this day in...

1979 Iranians Take Hostages At US Embassy
Iranian students stormed the US Embassy in Tehran on November 4th, 1979. They were angered that the US allowed the deposed Shah of Iran to receive medical treatment in the US. They threatened to murder hostages if any rescue was attempted. The Ayatollah Khomeini, leader of the fundamentalist revolutionaries, took full control of the country a few days later when the interim leader resigned. He released all non-US hostages and all women and minority Americans. He said that these were all groups who suffered oppression at the hands of the US. He continued to hold 52 Americans hostage. President Jimmy Carter attempted to obtain release of the hostages by diplomatic means but was unable to do so. A rescue attempt on April 24, 1980 failed terribly and cost the lives of eight US military personnel. In July the former Shah died of cancer but the Ayatollah was relentless. When Ronald Reagan was elected, Algerian intermediaries were able to successfully negotiate an agreement and on the day of his inauguration, January 20th, 1981 the 52 were released. $3 billion in frozen Iranian assets were also released and the US promised a further $5 billion in financial aid. The hostages' ordeal had lasted 444 days.



Thanks for reading Goodies to Go!

 




Archive Home Page.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date