I love JavaScript. Seriously. I'm glad that it has finally come into it's own as an integral part of AJAX, and Spry (for you ColdFusion users out there). There are lots of uses for JavaScript in real world web applications, for many reasons: it's clean, neat (as neat as the programmer, anyway), fast, and convenient. Granted, there is a bit of a learning curve to JavaScript, but you kind of have to expect that.
To create functions in JavaScript, all you have to do is name the function and decide whether or not you'll be passing in any arguments.
The steps to do this are below...try it out!
1. Think of what you want to do that JavaScript can do for you, like tell you the form element that you click on.
2. Give the function an easy name to remember, like getElement.
3. For this, you'll need to pass in an argument (or two, we'll see). Trust me, this is easy.
4. Decide the way that you're going to call the script. In this particular case, it will be by the onClick event of the form element.
5. Write it up!
The JavaScript will look something like this:
<script language="javascript">
function getElement(typ, nam, val) {
alert("The " + typ + " named " + nam + " with a value of " + val + " was clicked!");
}
</script>
I told you this was easy! Next is to determine the form element. We'll use a button, since that came to mind first.
The button will look like this:
<input type="button" name="somename" value="Click me!" onClick="getElement(this.type, this.name, this.value)">
You can see from that example that we are passing into the function the following 3 things IN ORDER: the type of the element, the name of the element, and the value of the element. The function takes these things and shoots them back out when requested. Good thing to note here too...the concatenation character for JavaScript is a plus sign (+). You can tie whatever you want together, as long as that character is there.
To assign string variables in JavaScript, use the following syntax: var variable = "some_value";
To assign numeric variables in JavaScript, use the following syntax: var variable = 1234567890;
The difference, of course, is that the string declaration has quotes, where the numeric does not. It is possible to leave off the var statement, but for good programming practice, go ahead and put the var in there.
To debug using JavaScript, use the built-in generic functions that JavaScript provides: the alert() function.
Example:
<script language="javascript">
var str = "some_value";
var num = 1234567890;
alert("The value of str is " + str);
alert("The value of num is " + num);
</script>