» in my experience...

» home | about | contact | résumé
» archives | donate | rss syndication

»
»
Great Falls (on the Potomac River) is a boiling monster that people actually Kayak down.


Communiblog Communiblog expressed as RSS 2.0
Here at IMX
Memes R' Us
freetheaudio2.jpg
SuperNova 1987A from 1994 to 2003
GarageBand

Category Archive » JavaScript

Detecting alphanumeric characters in JavaScript.
[ January 30, 2004 | Permalink | 4 Comments | 0 TrackBack | TB URL ]

It's 2004 already and just yesterday I wrote a JavaScript function to tell if a character passed into the function is an alpha-numeric character. One would think that after writing JavaScript for several years that the need for this check would have come up already (and furthermore that there would be a built in method in the language, but that's not the case).

I approached the problem by using ASCII character codes. If you have BBEdit, there's a pallette that shows all of those code next to their characters, so I used that to write an annoyingly long if statement with four "or" statements and two "and" statements imbedded in an or statement. Annoying, but effective. Here it is...

function alphaNumericCheck(theChar) {

	if ((theChar < 48) || (theChar > 122) || 
	   ((theChar > 57) && (theChar < 65)) || 
	   ((theChar > 90) && (theChar < 97))   ) {
		return false;
	} else {
		return true;
	}
}
To call the function, you would say something like...
<input type="button" name="foo" value="my button"
    onclick="alphaNumericCheck(this.value.charCodeAt(0))">
The part that says charCodeAt(0) will return the ASCII number for the character at the zeroth position in the string (the first character). The function will take that character and return "false" if it's not a number, a capital letter or a lowercase letter, and "true" if it is alphanumeric. Try it.




Getting form values for validation.
[ September 04, 2003 | Permalink | 1 Comments | 0 TrackBack | TB URL ]

Here's a quick little JavaScript that steps thru a form and reports the value of each element within that form, whatever the length of the form might be. This is a pretty easy little script to write, but I figured that since I had the need for it, someone else might too. The script looks like this...

function reportFormElements(obj)  {

for (var i = 0; i < obj.length; i++) {

	if (obj.elements[i].type == 'checkbox') {
		alert(obj.elements[i].checked);
	}
	else {
	alert(obj.elements[i].value);
	}
	
  }

}
The basic gist is, for each actual form element in the form, look at the value of the form element and alert that value. If it's a checkbox, then investigate the 'checked' attribute.

There are several ways to do this sort of thing, and one of them reports the value of each child node in the named form, including text nodes, html nodes. We don't want that, and only want to interrogate the actual form elements. A sample form is below, go ahead and try it...





checkbox



Is the setAttribute() method broken in IE?
[ August 05, 2003 | Permalink | 16 Comments | 0 TrackBack | TB URL ]

In a recent bit of development work, we discovered the beauty and pain of the setAttribute() method. Specifically, we wanted to dynamically create more form elements for people to fill out without having to go back to the server and add in the HTML. So, we do a createlement() and then add in the various attributes that make up an input box. Here's the basics...
  var input = document.createElement("INPUT");

  input.setAttribute("type","text");
  input.setAttribute("name","myinput");
  input.setAttribute("id","myinput");
That makes a new input element, and then sets all of the attributes and their values. The result should be something like this...
  <input type="text" name="myinput" id="myinput">
You can try that code right here...
When you click on "Add an Input" some more complex JavaScript than quoted above will execute, and if you are using Navigator, Safari or Mozilla, you will get a new input with all if its necessary attributes defined and populated. The innerHTML will be alerted so you can verify that. Try it, and then view the page source to see what the code is doing.

Notice that I used the word "should" in the my comments above. I say the 's' word for a couple of reasons. Internet Explorer 6 on Win 2k Pro doesn't set any of the attributes. And Internet Explorer 5.2.3 for Mac OSX does something even worse, it throws a JavaScript error on the attempt to set the type attribute. Scouring the net for answers yielded frustrating results.

One particularly delicious find mentions that the Microsoft Developer site provides code that doesn't execute. When I run the code at that link, I get an error at the attempt to set the type attribute. The MSDN even talks about the method as if it were fully supported, but I'm not so sure about that. The only working example I could find seems to be completely IE/Windows specific and mentions that "his method requires an object participating in persistence".

My conclusion is that the setAttribute method is not fully supported in Internet Explorer. So, we resorted to workarounds, and found one. If you do a createElement("SPAN") and then pump it full of innerHTML and then append that to something, you will get your desired effect. But, that's at the price of using non-DOM code.

If anyone else can shed any more light on this, please do. My knowledge on the subject is anecdotal and derived from experimentation. Other data includes weird comments like the following from O'Reilly...

"The book says that the setAttribute() method in IE4 through 5.5 uses propertynames instead of attributenames. I experienced that the same behaviour holds for IE6.0 for PC."
Again, please let me know if you know anything that hasn't been mentioned here already.


cells[] array broken in Safari (?)
[ June 26, 2003 | Permalink | 6 Comments | 0 TrackBack | TB URL ]

Safari reports the length of the cells[] array of a table row as zero, even if it has multiple cells. Look at the table below, if you mouse over it in a Gecko browser, or IE, you will see the background color of the table cells turn color. We do this by placing an onmouseover in the TR tags...
<tr onmouseover="color(this)">
And that "color" function takes over and says...
function color(obj) {

	for (var i=0; i < obj.cells.length; i++) {

		obj.cells[i].style.backgroundColor = '#FFFFCC';
	}
}
So, onmouseover, the TR object gets passed and the function runs a loop using the length of the TR cells[] array as a stop point. In each iteration of the loop, it sets the backgroundColor to a light yellow and then we use an onmouseout to clean up after it, using almost the same exact function, only with a different name and different color (in this case, light grey, or #CCCCCC).

_Row_1_Cell_1_ _Row_1_Cell_2_ _Row_1_Cell_3_ _Row_1_Cell_4_ _Row_1_Cell_5_ _Row_1_Cell_6_
_Row_2_Cell_1_ _Row_2_Cell_2_ _Row_2_Cell_3_ _Row_2_Cell_4_ _Row_2_Cell_5_ _Row_2_Cell_6_
_Row_3_Cell_1_ _Row_3_Cell_2_ _Row_3_Cell_3_ _Row_3_Cell_4_ _Row_3_Cell_5_ _Row_3_Cell_6_
_Row_4_Cell_1_ _Row_4_Cell_2_ _Row_4_Cell_3_ _Row_4_Cell_4_ _Row_4_Cell_5_ _Row_4_Cell_6_

It's a part of DOM1 and supported back from Nav4 and IE4, so I'm guessing this is an oversight(?) Which isn't to surprising, because this isn't one of those make or break implementations, but it is REALLY useful for helping users track across an HTML table of financial data.

[I don't mean to pick on Safari this week, I just happen to be dealing with it a lot and am finding some issues. I'm trying to help out by writing test cases and send them to the mother ship.]

[Update: Safari 1.1 doesn't fix the cells[] array.]
[Update: Safari 1.2 (which is Panther only) fixes the cells[] array.]


Lesson Learned.
[ June 26, 2003 | Permalink | 3 Comments | 0 TrackBack | TB URL ]

At work we have an internal-only web application that helps us (and by us, I mean the 120 person organization I work within, not the entire corporate entity) manage are our assets, hosts, and other operations oriented information. It's our lynch pin web app actually, and now, due to the one point oh release, it is my task to make sure it's compatible with Safari.

This is how yesterday's discussion about the getYear() method started. We are using that call in one script to deal with population of date fields (everything is tracked, and everything gets a time stamp). This effort is a classic example of why JavaScript, new browsers, and NOT following standards can cause extra work down the line.

Our server logs tell us that about 20 percent (I don't remember the exact amount, but it's much larger than "non trivial") of our users are Safari users, so this compatibility effort is essential. The saving grace is that the date functions we/I have written, are all in one place and sufficiently abstracted, and that helps me do less work. I had to add two lines of code to fix stuff. The hard part was doing the forensic work via alert() calls.

If I was smarter (and didn't use deprecated date methods), I wouldn't have had to make any edits, and Safari would have been auto-supported. Lesson learned.

Many thanks to those who posted yesterday.


getYear() in Safari == getYear() in Navigator 4.x
[ June 25, 2003 | Permalink | 8 Comments | 0 TrackBack | TB URL ]

Ok, so this is weird, and I don't know why it was done this way (maybe Dave can explain), but Safari 1.0 returns the same value for the getYear() method that Netscape 4.x does, 103. Check this script out and then go ahead and click the button to see what it returns...

<script type="text/javascript" language="Javascript1.2">

function showYear() {
	var nowX    = new Date();
	var theYear = nowX.getYear();
	alert(theYear);
}

</script>
Try it:

So, you should have seen a modal dialog box with "103" in it (assuming you have your system clock set correctly), which is the current year, minus 1900 . That's how Navigator did the getYear() method. Why does Safari do that? There must be some (good? bad?) reason, and whatever it is, we still have to deal with it, and this is one way to go about it. First, we can do some browser detection for Safari like we do for Navigator 4.x...
var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0
                && parseFloat(navigator.appVersion) >= 4
                && parseFloat(navigator.appVersion) < 5) ? 1 : 0;
And we can do something similar for Safari by saying...
var isSafari = (navigator.userAgent.indexOf("Safari") >= 0) ? 1 : 0;
This basically says that the var "isSafari" is equal to "1" if the string "safari" occurs in the navigator.userAgent object. If it doesn't, then the value is 0, and later on we can use that value to say...
if (isMinNS4 || isSafari) { theYear += 1900; }
Which says that if it's Nav 4 or Safari then make "theYear" equal to itself plus 1900. And even us forensic JavaScripters should be able to figure out that 1900 + 103 = 2003. So, to get Safari to tell you what year it is, we can use this function...
<script type="text/javascript" language="Javascript1.2">

function showYear() {

	var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0
	                && parseFloat(navigator.appVersion) >= 4
	                && parseFloat(navigator.appVersion) < 5) ? 1 : 0;
					
	var isSafari = (navigator.userAgent.indexOf("Safari") >= 0) ? 1 : 0;

	var nowX    = new Date();
	var theYear = nowX.getYear();

	if (isMinNS4 || isSafari) { theYear += 1900; }

	alert(theYear);
}

</script>
Try it:



A JavaScript Safari.
[ February 23, 2003 | Permalink | 1 Comments | 0 TrackBack | TB URL ]

Apple has posted an article about JavaScript support in Macintosh based browsers, and Safari supposedly scores well (but doesn't win). In my experience, the JavaScript engine is totally screwed up when it comes to dealing with forms, especially when doing client side validation onSubmit. In an internal web app I work with, we have a checkbox that gets its state checked to do an eval on another form element. No matter which state it's in, it gets tripped off for some reason.

I can't even begin to support Safari until the JavaScript engine is fixed, and hopefully the final production version of Safari will be pretty solid, but even then, I know I'll be tweaking our scripts. Just call me Sisyphus.


Setting a maxlength on a textarea.
[ February 15, 2003 | Permalink | 31 Comments | 0 TrackBack | TB URL ]

On a mailing list last week someone asked about placing a maxlength on a <textarea> which most HTML munkies will know is not a legal (or supported) attribute of that tag. Someone chimed in making that point and suggested that the person get familiar with the HTML 4.01 DTD. That advice is in the vein of 'if you teach a man to fish, you feed him for a lifetime.' I'm going to take the other tack and give the man a fish. [more...]


Fab.
[ February 10, 2003 | Permalink | 5 Comments | 0 TrackBack | TB URL ]

konfabulator is one of those little things that I really got to play with, right now. One really impressive thing about it is the website, which lends a lot of credibility to the app, and I haven't even downloaded it yet. Very professionally designed and well rounded websites are a nice change from the unwieldy web app I'm working on these days (ever changing = never perfect). However, the Konfabulator site is butt ass slow and all of the urls are different for pages, examples and downloads, etc.

I'm not sure why, but different domain names on different pages of a site makes me trust that site less. Why do you need one page of the site to live at an entirely different domain? I understand putting a file to download at a diff site (such as Akamai) for caching or download speed, but other normal pages of the site should be within the same domain. I don't know why, but it bugs me.

Who cares though, it all runs on JavaScript, and I know JavaScript, so I'll be tinkering with this soon.


You need a crutch when your leg is broken.
[ June 18, 2002 | Permalink | 0 Comments | 0 TrackBack | TB URL ]

ScottAndrew wonders what he really feels about JavaScript crutch libraries. I don't. I like them, welcome them and hope people learn from them. Personally, I find myself in a fire drill environment where a solution to a problem has to come as quickly as possible (sound familiar?). I keep a directory of old JavaScripts on my machine as reusable code libraries, but of course, as time goes by, they go stale, and Murphy's Law says I'll need the most stale script on a moments' notice. If I can get that working with minimal effort and deliver reliabel, functioning code, then I've put out the fire. When I have time, I go back to make the code clean, elegant and proper. I'll call this being resourceful.

Scott's point is not lost on me though, and I agree that correct, modern, validated, tolerant and gracefully degrading code is a best practice. Sometimes you just have to fill in the cracks and repave later (time and budget permitting).


Another diff in browser implementations.
[ May 13, 2002 | Permalink | 1 Comments | 0 TrackBack | TB URL ]

If you do a comparison of "08" (zero and any integer, eight is our example here) with "8" in javascript, you will find that Internet Explorer will say they are the same, and that Mozilla will say they are different. So you have to do a parseInt() on a variable containing "08" to get a comparison to a variable containing "8" to return 'true'.


JavaScripting is an anecdotal art.
[ December 26, 2001 | Permalink | 0 Comments ]

I've been working with JavaScript for several years and was pleasantly surprised to find the new edition (4th) of the O'Reilly JavaScript book on the shelf at Borders. As expected, the book is pretty well organized, and lets you know what calls can be made in what browsers. But, as always, the art of JavaScritpting in the real world is not so predictable.

One resource I have used in the past is the FAQTs JavaScript Knoweledge Base. The thing I like about the site is that it's a question and answer architecture. Sometimes I will find a question similar to my own, and look at the examples that answer my question. This sort of resource allows the application/functionality prototyper (that's me) to get something working in a minimum of time.


MovableType AmphetaDesk
NetNewsWire BlogTree Subscribe with Bloglines RSS Feed
Copyright © 2001 - 2003 by Daniel Kapusta