The following Javascript libraries are in the core.js library that ships with Alpha Five. All of the functions below are in the core.js library. These functions are useful if you are writing hand-coded Ajax applications or if you are writing Javascript event handlers in the built-in components.
In the case of the built-in components (e.g. the Grid), the core.js library is automatically included in your pages and there is no need for you to specify a link to the library. For pages that you write yourself, you can link the library into your page as follows:
<script type="text/Javascript" src="Javascript/core.js"></script>
The following functions can be used to get pointers to elements in an HTML document.
The $() function gets a pointer to elements in the HTML. It takes an arbitrary number of arguments, each a string with the ID of the element you wish to get a pointer to. If you pass it a single ID, the function will return a pointer to that element. If you pass it multiple IDs, the function will return a Javascript array of the HTML elements. If an element with the ID specified does not exist, the function will automatically look for an element that has a NAME of the passed in string, and return it.
The $() function is a convenient alternative to the native Javascript getElementById() function.
Examples:
$('firstname').value = 'Fred';
var p = $('lastname');
p.value = 'Smith';
/*Get an array of pointers to elements on the page */
var arr = $('firstame','lastname','city','state','zip');
arr[0].value = 'Fred';
arr[1].value = 'Smith';
The $n() functions gets elements in the HTML. It takes an arbitrary number of arguments, each a string with the NAME of the element you wish to get a pointer to. Getting elements by NAME returns an array because the NAME attribute is used to describe groups of controls - such as radio and checkbox groups. Therefore, even if there is only a single element with the given NAME, it will be returned inside a Javascript array. If you pass it a single NAME, the function will return a Javascript array of pointers to the elements that match the NAME passed in. If you pass it multiple NAMEs, the function will return a Javascript array of arrays of the HTML elements. If an element with the NAME specified does not exist, the function will automatically look for an element that has a ID of the passed in string, and return it.
Examples:
/*Assume that you have two radio buttons with choices 'Male' and 'Female'. Each radio button has a unique ID, but they both have the same NAME, 'gender' */
var genderInputs = $n('gender')
/*Select the first radio button in the group*/
genderInputs[0].checked = true;
The following functions can be used to get and set attributes and values of HTML elements. The ELEMENT argument that is passed in can in all cases be a pointer to an HTML element, or the ID or NAME of an HTML element.
The $ga() function retrieves an attribute or multiple attributes from a single element or multiple elements. The first parameter is a string with the ID or NAME of the element, a pointer to an HTML element, or an array of either of the previous. The second parameter is a string with the name of the attribute you wish to read, or an array of attribute names. If you pass in a single element, and a single attribute name, the return value will be a string with the attribute value. If you pass in a single element and an array of attributes, the return value will be an array of attribute values. If you pass in an array of elements and an array of attributes, the return value will be an array of arrays of attributes - each top level entry in the array being an array of values for the corresponding element passed in.
Examples:
/*This example reads the value of a built-in attribute. Since the attribute is built-in, it could also have been read directly.*/
alert($ga('firstname','title'));
/*Now, read the attribute directly (which we can do, since 'title' is a built-in attribute)*/
alert($('firstname').title);
/*The $ga() function's primary purpose is to read user-defined attributes. Assume that want to read the value of an attribute called 'fieldIsDirty'.*/
alert($ga('firstname','fieldIsDirty'));
/*$ga() returns an array if you pass it an array of IDs*/
var fieldArray = ['firstname','lastname','company'];
var arr = $ga(fieldArray,'fieldIsDirty');
/*Now, loop through the array and report on which elements are dirty.*/
for(var i = 0;i<arr.length;i++) {
if(arr[i] == 'yes') alert(fieldArray[i] + ' is dirty');
}
The $sa() function sets an attribute or multiple attributes for a single element or multiple elements. The first parameter is a string with the ID or NAME of the element, a pointer to an HTML element, or an array of either of the previous. The second parameter is a string with the name of the attribute you wish to set, or an array of attribute names. Behavior of arrays of elements or attributes is much the same as with the $ga() function.
Examples:
/*Set the value of the user-defined 'fieldIsDirty' attribute.*/
$sa('firstname','fieldIsDirty','yes')
/*Set the 'fieldIsDirty' attribute for multiple elements.*/
$sa(['firstname','lastname','company','address','city','state','zip'],'fieldIsDirty','no');
/*Set multiple attributes for an element. 'attribute1' is set to 'value_of_attribute1' and 'attribute2' is set to 'value_of_attribute2'.*/
$sa('input1',['attribute1','attribute2'],['value_of_attribute1','value_of_attribute2']);
The $gvs() function gets the value from a single 'conceptual' element (get value single). A 'conceptual' control in the HTML can be represented by multiple physical elements. For example, a radio button with the choices 'Green', 'Red' and 'Blue' can be thought of as a single 'conceptual' control, but the HTML will contain three physical elements, one for each of the options.
If the control passed in has multiple values, as with a SELECT set to allow multiple selections, or a checkbox group, the function will return an array of values. Otherwise it will return a string of the value.
You can also use $gvs() against elements that are not form controls - the function will return the innerHTML property of the element.
Examples:
/*Assume that the HTML contains this markup for a radio button group
<input type="radio" name="FavoriteColor" value="Red" id="radio1" /><label for="radio1">Red</label>
<input type="radio" name="FavoriteColor" value="Blue" id="radio2" /><label for="radio2">Blue</label>
<input type="radio" name="FavoriteColor" value="Green" id="radio3" /><label for="radio3">Green</label>
*/
/*Get the selected value in the 'FavoriteColor' radio button control*/
alert($gvs('FavoriteColor'));
/*Assume that the HTML contains a SELECT control that allows multiple selections.
Red and Green are currently selected
<select id="FavoriteColorSelect" size="5" multiple="multiple">
<option selected="selected">Red</option>
<option>Blue</option>
<option selected="selected">Green</option>
</select>
*/
/*Get the current selections in the SELECT control into an array*/
arr = $gvs('FavoriteColorSelect');
/*Assume that the HTML contains a SPAN with an ID of 'span1'
Display the innerHTML property of the span.*/
?alert($gvs('span1'));
The $svs() function sets the value of a single conceptual element (set value single). A 'conceptual' control in the HTML can be represented by multiple physical elements. For example, a radio button with the choices 'Green', 'Red' and 'Blue' can be thought of as a single 'conceptual' control, but the HTML will contain three physical elements, one for each of the options.
If the control passed in can have multiple values, as with a SELECT set to allow multiple selections, or a checkbox group, then you must pass in an array (rather than a single value), and the function will set the control to the values in the array.
You can also use $svs() against elements that are not form controls - the function will set the innerHTML property of the element.
In the case where the page contains multiple 'conceptual' controls with the the same name (e.g. a radio button group called 'Gender' might appear in two different forms on the page), you can specify the optional PARENT_ELEMENT parameter to identify which particular radio button group you want to address. The PARENT_ELEMENT can be any element that contains the 'conceptual control'.
The $svs() function can be used with a hyperlink control. By passing in an array for the VALUE parameter, you can set the url, hyperlink text, and tooltip.
The $svs() function can be used with images (IMG tags). By passing in an array for the VALUE parameter, you can set the src, and tooltip.
Any other element that is not a form control, hyperlink or an image (e.g. a span, div, etc.) will be populated with text (i.e. the VALUE that you pass in will be used to set the innerHTML of the object and any '\n' in the VALUE will converted to '<br />' tags.
Examples:
/*Assume that 'FavoriteColors' is a SELECT control that allows multiple selections.
Select the Red and Green entries.*/
$svs('FavoriteColors',['Red','Green']);
$svs('span1','Set the text in the span');
/*Assume 'gender' is a RADIO BUTTON group. i.e. there are two radio buttons with unique ids, but both radio buttons have the same name - 'gender'.*/
/*Get an array of elements - one for each radio button element in the RADIO BUTTON group.*/
var genderElements = $n('gender');
$svs(genderElements,'Male');
/*However, the above example could be accomplished much more simply using this code.*/
$svs('gender','Male');
/*Assume that a form contains this markup*/
<form id="form1">
<input type="radio" name="sex" value="Male"/>Male<br />
<input type="radio" name="sex" value="Female"/>Female<br />
</form>
<form id="form2">
<input type="radio" name="sex" value="Male"/>Male<br />
<input type="radio" name="sex" value="Female"/>Female<br />
</form>
/*To set the value for the radio button control group inside 'form1' (but not inside 'form2')"*/
$svs('sex','Male','form1')
/*Alternatively, */
var ele = $('form1');
$svs('sex','Male',ele);
/*Assume that your page contains this hyperlink*/
<a id="link1" href="http://www.alphasoftware.com" title="Go to Alpha Software">Alpha Software</a>
/*To change the hyperlink URL, (without changing the text or tooltip:*/
$svs('link1','http://www.google.com');
/*To change the url, text and tooltip*/
$svs('link1',['http://www.google.com','Google','Go to Goole']);
/*Assume that your page contains this image*/
<img id="image1" src="picture1.jpg" title="A picture of Boston"/>
/*To change the image src*/
$svs('image1','picture2.jpg');
/*To change the image src and tooltip*/
$svs('image1',['picture2.jpg','A picture of Ithaca']);
The functions below provide an easy way to get and set the in-line style, can class of HTML elements. The passed in argument of "ELEMENT" can be a pointer to an HTML element, or the ID or NAME of an HTML element. The functions will automatically fetch the element if you pass in an ID or NAME.
The $gs() function gets the in-line style of the passed-in element(s), and returns the CSS text.
Example:
alert($gs('fname'));
/*The above example would return a string that might look like this:
font-family: arial;
font-size: 10pt;
*/
The $ss() function sets the in-line style of the passed-in element(s). It takes a second parameter of a JSON (Javascript Object Notation) object of the style attributes to set.
Example:
/*Set the control's font family and font weight.*/
$ss('firstname',{fontFamily: 'arial', fontWeight: 'bold'});
/*The above example is a shortcut for this technique for setting the in-line style.*/
var ele = $('firstname');
ele.style.fontFamily = 'arial';
ele.style.fontWeight = 'bold';
The $scn() function sets the class name of the passed-in element(s). This will overwrite any class names the already being using by the element(s). Contrast this with the $acn() function which adds the class name to the element. (Note: An element can have more than one class name.)
Example
/*Set the class name of the 'firstname' element.*/
$scn('firstname','formInput');
/*Set the class name of multiple elements. Any existing class names for the elements will be removed.*/
$scn(['firstname','lastname','address','city','state','zip'],'formmInput');
The $acn() function adds the class name to the passed-in element(s). This will not overwrite any class names the already being using by the element(s). Instead, the new CSS classes will be used in addition to the class names already in use on the element(s). The added class name is the added as the last class name in the list of class names for the element. This means that any style attribute that duplicates a style attribute in one of the existing class names will override the existing style attribute.
This function is particular useful for adding an 'error' class name to an element when you want to highlight an error. Another typical use of this function is to add add some temporary styling to an element, such as when the element gets focus.
Examples:
/*Assume that after a validation error, you want to indicate an error. The 'inputError' class might set the element's border color to red.
The 'firstname' control already has a class name (such as 'formInput'). You want to keep this class name, and add the error class name as an additional class name.*/
$acn('firstname','inputError');
/*Add to the class names of multiple elements.*/
$acn(['firstname','lastname','address','city','state','zip'],'inputError');
The $rcn() function removes the class name from the passed-in element(s). This will only remove the specified class name. You might want to use this to remove some temporary styling to an element, such as a focus, or error style. This function is typically used after the $acn() function has been used to add a class name to an element.
Examples:
/*Assume that you previously added the 'inputError' class name to an element to indicate that a validation error had occurred. Now, assume that the user has
corrected the error and you want to remove the 'inputError' class name from the element. */
$rcn('firstname','inputError');
/*Remove a class name from multiple elements.*/
$rcn(['firstname','lastname','address','city','state','zip'],'inputError');
The functions listed below make it easier to scroll to, position, and size elements in the HTML.
The $po() function positions one element relatively to another. The first parameter in the element you wish to position.
Important: The 'position' CSS attribute of the element you wish to position must be set to 'absolute'. Otherwise the element's position cannot be altered.
The second parameter is the element you wish to position relatively to.
The third parameter defines where you would like the child element to be positioned relatively to the parent element. It can either be a number (see image below), or a keyword string (see table below).
In the image below, the blue box represents that element that you are positioning relative to. There are 21 different numbered position shown on the image. For example, position 1 will position relative to the top left corner of the element. Position 8 will position relative to the top right corner of the element. Position 20 will position centered on the height of the element on the right edge of the element.
The named positions (e.g. 'dropdown', 'flyout', etc.) will take page size into account, and automatically change the positioning of the element if there is not enough room.
The MAINOFFSET and SUBOFFSET parameters allow you to optionally tweak the positioning of the element by specifying an offset (in pixels) from the element's default position.
In the below image the longer offset orientation arrow represents the main offset, and the short arrow represents the sub offset. So for example, if you specify position 1, with a MAINOFFSET of 10, the right edge of the element that is being moved will be 10 pixels away from the left edge of the element you are positioning relative to. If you specify a SUBOFFSET of -5, then the bottom of the element you are positioning will be 5 pixels closer than normal to the top of the element you are positioning relative to.
| Keyword | Description |
| dropdown | Positions the child element relative to the bottom left corner of the parent object. (Will position above if there is insufficient space below the parent object.) |
| dropdown-right | Positions the child element relative to the bottom right corner of the parent object. (Will position above if there is insufficient space below the parent object.) |
| flyout | Positions the child element so that the left side of the child object is positioned relative to the top, right side of the parent object. (Will position left of parent if there is insufficient space to the right of the parent object.) |
| flyout-bottom | Positions the child element so that the left side of the child object is positioned relative to the bottom, right side of the parent object. (Will position left of parent if there is insufficient space to the right of the parent object.) |
In the diagram below, the 'long' arrow indicates the MAINOFFSET parameter
and the 'short' arrow indicates the SUBOFFSET parameter for the $po()
function.
Examples:
/*Position an element directly over another element.
Assume that 'overlay' is some object, perhaps a DIV with a transparent fill.
Assume that 'parentObject' is the object that you want to cover with some other object.
We want to position the overlay relative to the top left corner (position 6 in the diagram) of the parent object.
*/
$po('overlay','parentObject',6);
/*Position an element directly over another element and resize the overlay object so that it is the same size as the parent object.*/
$po('overlay','parentObject',6);
$sor('overlay','parentObject','wh');
/*Position an object as a 'dropdown' (position 14). However, if there is not sufficient space for the dropdown object below the parent object, then automatically use position 2.*/
$po('dropdownList','parentObject','dropdown');
/*Position an object below the parent object and centered in the width of the parent object.*/
$po('dropdownList','parentObject',21);
/*Position an object 20 pixels below the parent object and 10 pixels to the left of the center of the parent object.*/
$po('dropdownList','parentObject',21,20,-10);
The $sor() function sizes an element relatively to another element. I.e. the function makes one object the same size as another object.
The first parameter in the element you wish to size.
The second parameter is the element you wish to size relatively to.
The third parameter defines what properties you would like to size. It takes a string that contains 'w' and/or 'h'. For example, 'wh' if you want to size width and height, 'w' if you want to size width only.
The four and fifth parameters allow you to optionally specify pixel offsets. For example, if you specify to size the object to be 10 pixels wider and 5 pixels higher than the reference element, you would specify a FIRSTOFFSET of 10 and a SECONDOFFSET of 5 (assuming that you specified the TYPE as 'wh'). If you specified the TYPE as 'hw', then you would swap the order of the offsets.
Examples:
/*Sets the child object to have the same width and height as the parent object.*/
$sor('childObject','parentObject','wh');
/*Sets the child object to have the same width + 6 px and same height + 4 px as the parent object.*/
$sor('childObject','parentObject','wh',6,4);
/*Same as above example, but since TYPE was specified as 'hw' (and not 'wh'), the order of the offsets is swapped.*/
$sor('childObject','parentObject','hw',4, 6);
The $swto() function scrolls the window to the specified element.
Example:
/*Assume that the page contains a DIV that has an ID of 'detailView' that may not be visible because the browser window is not high enough. After refreshing the contents of this DIV you want to scroll it into view.*/
$swto('detailView')
The core Javascript library provides several functions for adding and removing events from objects. Many developers like to create 'clean' HTML that does not have any Javascript events embedded in the HTML. This provides a nice separation between the HTML layout and the behavior of the HTML page.
The functions in this section describe how you can use Javascript to attach (i.e. bind) Javascript code to the various element events in your HTML page.
This methodology is often referred to as 'unobtrusive' Javascript because the Javascript which controls the HTML does not clutter up the HTML markup and is kept separate from the HTML.
The $e.add() function allows you to add an event to a single or multiple HTML elements.
The first parameter is an HTML element, and ID or NAME, or an array of HTML elements, IDs, and/or NAMEs.
The TYPE parameter (2nd parameter) is the type of event. These events are standard DOM events (minus the "on"), like 'click', 'mousedown', 'mouseup', 'keydown', 'blur' etc. The table below show a complete list of event names.
| Event Name | Description |
| click | When the user clicks on an element. |
| dblclick | When the user double clicks on an element. |
| mousedown | When the user presses the mouse down on an element. |
| mouseup | When the user releases the mouse button after pressing mouse down on an element. |
| mouseover | When the mouse cursor moves over an element. |
| mousemove | When the mouse cursor is being moved over an element. |
| mouseout | When the mouse cursor leaves an element. |
| keypress | When the user presses a key. Will fire repeatedly while the key is being pressed. |
| keydown | When the user presses a key. Fires on the key down. |
| keyup | When the user presses a key and then releases it. |
| focus | When the user gives focus to an element. |
| blur | When a user 'blurs' an element. I.e. when an element looses focus. |
| change | When the user makes a change in a form element. |
| reset | When the user resets the data in a form using a 'Reset' button. |
| submit | When the user clicks a form's 'Submit' button. |
| scroll | When the user scrolls a scrollable element. This could be the page itself, of a DIV that has scroll bars. |
| resize | When the user resizes the browser window. |
| load | When the page is loaded. |
| unload | When the page is unloaded (i.e. when you navigate to another page, or the browser is closed). |
The FUNCTION parameter (3rd parameter) is the Javascript function you would liked to have called when the event occurs.
You can call the $e.add() function multiple times for a given element and event, allowing you to add multiple event handlers for the same event. For example:
$e.add('firstname','blur',validate1);
$e.add('firstname','blur',validate2);
When the 'firstname' element looses focus, the validate2() function will be called first (since it was the most recent event handler to be added), and then the validate1() function will be called next.
Note: When you add an event to an element that already has an event defined in the HTML, the event defined in the HTML will still execute, and will be executed before any events that are added using the $e.add() function.
When a DOM event (such as 'blur', 'keypress' etc.) occurs, the browser automatically stores relevant information about the event (such as what key was pressed, what is the mouse position, etc.) in the DOM event object. This object is automatically passed in as the first parameter to the Javascript function that is handling the event.
The DOM event object can also be used to stop an event from 'bubbling' (i.e. a 'click' event on a button that was contained in a DIV will first cause the button's onClick event to fire, then will cause the DIVs onClick event to fire and the will cause the page's onClick event to fire). You might want to prevent the event from bubbling up to the DIV and the page. You can do this by using the $e.stopEvent() function, passing in the DOM event object to this function.
The SCOPE parameter (4th parameter - optional) is an object scope to be passed into the function that handles the event. The scope object is passed in as the second parameter to the event handler function (the DOM event object is passed in as the first parameter). This is an advanced parameter.
The SCOPEOVERRIDE parameter (5th parameter - optional) is a true/false value for whether or not you would like the passed in scope to take the place of the HTML element in the "this." namespace.
Note: SCOPE and SCOPEOVERRIDE are advanced parameters that will rarely be needed.
The GROUPNAME parameter (6th parameter - optional) is a group name for the event. This is a 'convenience' feature. It can be used with the $e.removeGroup() function to remove multiple events from multiple objects. (Note: Your page might contain elements that have had events bound to them using the $e.add() function. If any of these elements are subsequently removed from the page (through setting innerHTML of a parent element, or through DOM manipulation), it is important to remove the events from these elements, or else a memory leak might occur.)
Examples:
Example 1
Assume you have the following HTML page. Notice that the HTML has two input controls ('id_fn' and 'id_ln') and that there are no Javascript events defined in the HTML.
We want to add a handler for the 'onBlur' event for both of these controls. When either of the controls looses focus, we want to call the blurred() function.
Notice that in the definition of the blurred() function, we show a parameter that is passed in (function blurred(e) ). The argument is the DOM Event object that is automatically passed in to the event handler. The DOM Event object has information about the event that triggered the function call.
<html>
<head>
</head>
<body>
<input id="id_fn" name="firstname"/>
<input id="id_ln" name="lastname"/>
</body>
</html>
<script type="text/Javascript" src="Javascript/core.js"></script>
<script type="text/Javascript">
function blurred(e) {
alert('ID:' + this.id + '\n Event type: ' +e.type + '\n Value in control: '
+ this.value);
}
/*Add the event handler for the 'blur' event to the 'id_fn' and 'id_ln'
elements.*/
$e.add(['id_fn','id_ln'],'blur',blurred);
</script>
Example 2
This example demonstrates how you can bind multiple event handlers to an event, and shows the order in which the event handlers are executed.
In this example, the HTML contains a definition for the onblur event for the 'id_fn' element. In addition to the event handler defined in the HTML, the Javascript code binds the msg2() function and then the msg3() function to the blur event for 'id_fn'.
If you load this page in a browser, when focus leaves the 'id_fn' element you will notice the following:
Notice that in the definition of the msg2() function we pass in the DOM event object and so the message box can display e.type (the type of the event that caused the event handler to be invoked). Also notice that the 'this' alias is implicitly passed in and can be used to get information about the control (such as it's ID - 'this.id', or current value - 'this.value')
<html>
<head>
</head>
<body>
<input id="id_fn" name="firstname"
onblur="alert('msg1'); return false;" />
<input id="id_ln" name="lastname"/>
</body>
</html>
<script type="text/Javascript" src="Javascript/core.js"></script>
<script type="text/Javascript">
function msg2(e) {
alert('ID:' + this.id + '\n Event type: ' +e.type + '\n Value in control: '
+ this.value);
}
function msg3(e) {
alert('msg3');
}
/*Bind the msg2() function call to the 'blur' event on the 'id_fn' and 'id_ln'
elemenets.*/
$e.add(['id_fn','id_ln'],'blur',msg2);
$e.add('id_fn','blur',msg3);
</script>
The $e.remove() function allows you to remove an event on a single or multiple HTML elements.
The ELEMENT parameter is an HTML element, an ID or NAME, or an array of HTML elements, IDs, and/or NAMEs.
The TYPE parameter is the type of event. This can be standard DOM events (minus the "on"), like "click", "mousedown", "mouseup", "keydown", etc.
The FUNCTION parameter is the Javascript function you was linked to the event.
Note: This function only removes event handlers that were added using the $e.add() function. It cannot remove event handlers that are specified in the HTML markup.
Examples:
//Assume that the $e.add() function had been previously called to add the 'validate1()' function to the 'onBlur' event for the 'firstname' control.
$e.remove('firstname','blur',validate1);
//Assume that the 'validate1()' function had been bound to multiple controls.
$e.remove(['firstname','lastname'],'blur',validate1);
Note: When you use the $e.add() command to add events, you can specify an optional 'group' name. This group name is used in the $e.removeGroup() function.
The $e.removeGroup() function allows you to remove events from elements that were initially set up with a 'group' name. This command is useful if you want to remove a large number of events from elements using a single function call.
Note: It is important to remove any events that were added to elements before destroying the HTML elements (either through direct DOM manipulation, or by setting the innerHTML of some containing element). For example, assume that your page has a large number of input controls. You use the $e.add() function to bind a validation event handler to the 'onBlur' event on all of these controls and you assig
Examples:
//Add some validation events to several form controls and assign an arbitrary group name of 'myForm'.
$e.add(['firstname','lastname','address','city','state','zip'],'blur',validateInput,null,false,'myForm');
$e.add('zip','blur',validateZip,null,false,'myForm');
//Now, 'zip' has two event handlers for its 'onBlur' event.
$e.add('zip','blur',lookupCity);
//Now, 'zip' has three event handlers for its 'onBlur' event. However, this last event handler is not part of the 'myForm' group.
$e.removeGroup('myForm');
//Now all control have no event handlers attached to the 'onBlue' event, except 'zip' which still has 'lookupCity()' as the event handler for the 'onBlur' event.
The $e.stopEvent() function allows you to stop an event from bubbling up through the hierarchy of elements on a page.
You pass in the event object variable that was passed into the function that is handling the event.
Example:
/*This adds an event handler for the 'onKeyup' event to both the document body, and an input called 'input1'.
If the user types a key in the input, the keypressInput() function will handle the event, and then the keypressBody() function
will ALSO handle the event (because the event 'bubbles' up through the hierarchy of element on the page. */
$e.add(document.body,'keyup',keypressBody);
$e.add('input1','keyup',keypressInput);
/*Now, assume that when the user types a key into the input, you want the keypressInput() function to be called, but NOT the keypressBody() function.
To do this, you must stop the 'onKeyUp' event from 'bubbling up'.
This is done by calling the $e.stopEvent() function inside the keypressInput() function. For example:
*/
function keypressInput(evnt) {
$e.stopEvent(evnt);
//Actual code you want to handle the keypress goes here.
//Note: the 'evnt' variable is always passed into a function that was bound using the $e.add() function.
//The 'evnt' variable contains information about the event that happened, such as mouse position, or key pressed.
}
$e.onLoaded is an optionally defined function that will be called after the page has been fully loaded, and the "$e" object has been fully initialized. This function can only be used once on a page. This function is useful if you want to execute some Javascript when a page is loaded, if that Javascript is dependent on the "$e" object being fully initialized.
For example, assume that you have a page with an auto-suggest input control. The auto-suggest control is instantiated using the "A5.AutoSuggest()" function. Assume that when the page is loaded, you want initial focus to go to this control. Assume that the control has an ID of "SUGGEST1". You might be tempted to put the following code in the BODY tag's "onload" attribute. For example:
$('SUGGEST1').focus();
However, this will not work because the "A5.AutoSuggest()" function which initializes the auto-suggest control has not yet executed. The auto-suggest control utilizes the "$e" object. We need to wait till the "$e" object has been fully initialized before we can set focus to "SUGGEST1". The "$e.onLoaded" function is how we solve the problem.
$e.onLoaded = function(){
$('SUGGEST1').focus();
}
Immediate if statement.
Example
var welcomeMsg = 'Hello ' + $if(sex=='Male','Mr.','Ms.') + $gvs('lastname');
/*The immediate if is more concise than using an if() statement, as shown below*/
var welcomeMsg = 'Hello ';
if(sex=='Male') {
welcomeMsg = welcomeMsg + 'Mr.';
} else {
welcomeMsg = welcomeMsg + 'Ms.';
}
welcomeMsg = welcomeMsg + $gvs('lastname');
Convert a string into a number. Non-numeric characters are stripped out. The default thousands separator is a comma and decimal separator is a period. However, you can specify the values to use by setting $u.decimal and $u.comma.
Example
var amountString = '$2,623.23';
var amountValue = $u.s.toNum(amountString);
var discountValue = amountValue * .9;
var amountEuropeanString = 'E2.623,23';
$u.decimal = ',';
$u.comma = '.';
var amountValue = $u.s.toNum(amountEuropeanString);
Convert a string into a logical. If a string is one of the following values (case insensitive), it is converted to true: true, t, yes, 1, .t.. Any other value is false.
Example
/*Assume that the page has in input control called 'married' in which
a user might have typed 'Yes'*/
var isMarried = $u.s.toBool($gvs('married'));
Trim the left of a string, removing spaces and any passed in characters.
Example
var string1 = ' this is a string with leading spaces';
string1 = $u.s.lTrim(string1);
var string1 = ' - this string has a leading dash';
string1 = $u.s.lTrim(string1,' -');
/*the resulting string is 'this string has a leading dash'. The leading spaces and - have been removed.*/
Trim the right of a string, removing spaces and any passed in characters.
Example
var string1 = 'this is a string with trailing spaces ';
string1 = $u.s.rTrim(string1);
/*resulting string is 'this is a string with trailing spaces'*/
var string1 = ' - this string has a leading and trailing dash and spaces - ';
string1 = $u.s.rTrim(string1,' -');
/*the resulting string is ' - this string has a leading and trailing dash and spaces'. The trailing spaces and - have been removed.*/
Trim the both sides of a string, removing spaces and any passed in characters.
Example
var string1 = ' - this string has a leading and trailing dash and spaces - ';
string1 = $u.s.aTrim(string1,' -');
/*the resulting string is 'this string has a leading and trailing dash and spaces'. The leading and trailing spaces and - have been removed.*/
Replace single or multiple strings in a string.
Example
var str = 'The boy wore a yellow shirt';
str = $u.s.tran(str,'boy','girl');
/* result is: 'The girl wore a yellow shirt'*/
str = $u.s.tran(str,['boy','yellow'],['girl','green']);
/*result is 'The girl wore a green shirt'*/
Fetch a given word from a string, based of a separator (the default separator is a space).
Example
var str = 'The boy wore a yellow shirt';
str = $u.s.word(str,2,'wore');
/* result is: ' a yellow shirt'*/
Pad a string with a passed in padding string. Optionally choose where the padding should be positioned, by passing in a fourth parameter of "l", "r", or "c".
Example
var str = 'hello';
str = $u.s.pad(str,11,'*');
/* result is: '******hello'*/
str = 'hello';
str = $u.s.pad(str,11,'*','r');
/* result is: 'hello******'*/
str = 'hello';
str = $u.s.pad(str,11,'*','c');
/* result is: '***hello***'*/
Replicate a string a given number of times.
Example
var str = 'bye';
str = $u.s.replicate(str,4);
/* result is: 'byebyebyebye'*/
Change the case of a string. Types can be:
Example
var str = 'hello world!';
str = $u.s.changeCase(str,'u');
/* result is: 'HELLO WORLD!'*/
str = $u.s.changeCase(str,'l');
/* result is: 'hello world!'*/
str = 'hello WORLD!';
str = $u.s.changeCase(str,'fu');
/* result is: 'Hello WORLD!'*/
str = 'hello WORLD!';
str = $u.s.changeCase(str,'furl');
/* result is: 'Hello world!'*/
str = 'hello WORLD!';
str = $u.s.changeCase(str,'wfu');
/* result is: 'Hello WORLD!'*/
str = $u.s.changeCase(str,'wfurl');
/* result is: 'Hello World!'*/
Convert a number into a string. The second parameter allows you to specify decimal places to round to. The optional third parameter specifies format flags. Format flags are:
The fourth and fifth parameters allow you to specify an optional prefix and suffix.
Example
$u.n.toStr(11222.152,2,',','$',' (US)')
/* result is: '$11,222.15 (US)'*/
$u.n.toStr(-11222.152,2,'(,','$',' (US)')
/* result is: '($11,222.15 (US))'*/
Convert a number into a place string (i.e. "1st", "2nd", "3rd", "4th", "105th"...)
Example
$u.n.toPlaceStr(23)
/* result is: '23rd'*/
Round a number to the given decimal place. The direction optional argument allows you to specify the direction you want to round. The "direction" flag has three possible values:
Example
$u.n.round(23.12142342342342,1)
/* result is: 23.1*/
$u.n.round(23.12,1,'u')
/* result is: 23.2*/
$u.n.round(23.18,1,'d')
/* result is: 23.1*/
Find a value in an array. If you specify the third parameter as true, the function will search the entire array, and return an array of matching indexes. Otherwise it will return the index of the first match found. The fourth parameter allows you to specify whether you would like to find exact matches, or any instances that contain the value passed in.
Example
var arr = ['one two','three','two three']
$u.a.find(arr,'three')
/* result is: 1*/
$u.a.find(arr,'three',true,false)
/* result is: [1,2]*/
$u.a.find(arr,'three',false,false)
/* result is: 0*/
Remove duplicate entries from an array.
Example
var arr = ['one','two','three','one','two']
$u.a.dedup(arr)
/* result is: ['one','two','three']*/
Assign the values from a base object to another. The first parameter is the object you want to assign to. The second parameter is the object you want to assign from. The optional third parameter is a true/false as to wether you would like to keep values that already occur in the object that is being assigned to, or whether you would like to overwrite them.
Example
var obj = {firstName: 'Bob', lastName: 'Thomas'};
var obj2 = {lastName: 'Duran', age: 32};
$u.o.assign(obj,obj2);
/* "obj" now equals: {firstName: 'Bob', lastName: 'Duran', age: 32}*/
obj = {firstName: 'Bob', lastName: 'Thomas'};
obj2 = {lastName: 'Duran', age: 32};
$u.o.assign(obj,obj2,true);
/* "obj" now equals: {firstName: 'Bob', lastName: 'Thomas', age: 32}*/
These Javascript functions are useful for users who want to hand code Ajax forms. The function allow you to submit values, create callbacks, populate specific controls, and reset forms.
The functions are designed to use the ID value of forms and controls. Therefore, every control, form, or other element should have an ID value. The exceptions are checkboxes, and radio buttons, where the control name can be used.
An html form element must be “prepared” before the other functions can gather information. When the page is initialized, this function should be the first run. The function adds and populates a couple new attributes to every control such as “a5isdirty” and “a5originalvalue”. These are required to allow the form to submit properly. When the form is initialized, the original value in the control is placed in “a5originalvalue” and “a5isdirty” is set to “false”. The function also adds some event handlers to each control to set the value if “a5isdirty” to “true” if the value in the control changes.
Example:
<script type="text/Javascript" language="Javascript">
<!--
function onPageInitialize()
{A5.form.prepare('my_FORM')}
//-->
</script>
<title>Title</title>
</head>
<body onload="onPageInitialize()">
<form id="my_FORM" name="my_FORM" method="POST" action="">
This is similar to A5.form.prepare(), however, it does not create the events or attributes. If the form was prepared previously, this function will reset all “a5isdirty” attributes to “false” and set all “a5originalvalue” attributes to the current value in the control. This is a useful function to run after a form is “cleared”
If keepOldValues is true, then the controls in the form are reset to the original values when the form was originally prepared.
This is the primary function to invoke to submit data from the page back to the server. This action is similar to pressing a submit button on a traditional form, but has additional functionality.
There are three required parameters
1. action' - name of the action to invoke in the .a5w page that handles the callback
2. 'formID' - the ID of the form
3. ‘url' - the URL of the .a5w page that will handle the callback
Action parameter
The action has a number of predefined values. All of the actions submit all of the input
values in controls inside of the specified form element as a POST. The action also submits additional values on every submit.
1. __FormAction – This is a variable submitted to define the action taken. Any submit action with place “submit” in this value. Any other action will place the action name, such as ‘initialize’ in the value.
2. __FormID – This is the ID of the firm submitted and matched the ‘formID’ input parameter.
3. a5DirtyRegions – This is the ID of any forms submitted that have ‘dirty’ values. This will almost always be the same as ‘__FormID’
4. a5RegionsDirtyValues – This is a list of controls that were found to be ‘dirty’. This is useful for updates to create update actions to only update field values that have changed.
Submit actions
1. submit:all – This action submits all of the original values in every field prefaced with the pointer ‘old.’ as well as the current values in every control. The ‘old’ values can be used in UPDATE statements and other actions if desired.
2. submit:dirty – This action is very similar to ‘submit:all, except only ‘dirty’ controls are listed and submitted. Values from ‘submit:all’ can be evaluated on the callback page to get the same data if required.
3. submit:new – This action just submits all current values in the controls. It does not submit the ‘old’ values.
formID parameter
The formID input specifies the ID of the form element that is being submitted. A single page may have multiple form elements, and it is necessary to indicate which form is eing submitted. This value will be in the submitted data as __FormID.
url Parameter
This is the URL of the page to call on submit. This is equivalent to the ‘action’ attribute of a form element which directs the submit action to open a particular page. This page or “callback” page contains xbasic code to evaluate and manipulate the data submitted. If the data is sent to the page with A5.form.submit(), the page code must test the value in __FormAction to determine what action was invoked. This would be a typical code snippet on the callback page to evaluate what code actions to take after submit.
dim __formAction as c = default ""
dim action as c
if __formAction = "Submit" then
if onFormValidate(local_variables())
afterFormValidate(local_variables())
end if
else if __formAction = "Initialize" then
onFormInitialize(local_variables())
end if
Note that a second possible input variable (‘action’) to define an action was specified. This will be examined in A5.ajax.callback()
Optional Fourth Parameter
In some cases, it is desirable to submit values that are not in controls within the specified form. These could be controls in another form element, a fixed value based on some condition, or any other value available to the page. These are the values that would be seen after the “?” in a URL, commonly referred to as the GET or query string. This parameter should have the same syntax as any GET.
For example, if the submit action is submitting to ‘calculatesale.a5w’ and you want to send additional parameters of ‘user=Joe’ and ‘date=20081010’ a normal form element could be:
<form action="calculatesale.a5w.a5w?user=Joe&date=20081010" method="post" name="form1" id="form1">
When using the function A5.form.submit() to submit all values from the form element ‘form1’, the function syntax would be:
A5.form.submit('submit:new','form1','calculatesale.a5w','user=Joe&date=20081010')
If a control is changed by user action, the event handlers created by A5.form.prepare() will set the control “dirty” when the user leaves the control However, often a control value is changed by some other action, such as a Javascript action on the page, an action such as a lookup or date picker. If the list of ‘dirty’ controls is important for some action, every changed control must be set ‘dirty’ or it won’t be listed. If the user didn’t directly change the value, the “dirty” attribute won’t be set. This function allows setting a control ‘dirty’. If a control has an ID value of “newdate”, this Javascript function call will set the ‘a5isdirty’ attribute to “True”.
A5.form.setCtrlDirty('newdate')
Select boxes or dropdowns are common controls on a page. This function allows populating a dropdown with values from a callback page.
There are four required input parameters
1. ‘eleId’ – This is the ID attribute of the select control
2. ‘curValue’ – this is the value to show as selected when the control is populated. If it is specified, the control will not show any “blank” or empty option. If it is not specified (value = “”), a blank option will be shown at the bottom of the list of options.
3. ‘data’ – this is the list of values used to create the option list. It is Javascript array object.
4. ‘clearExistingEntries’ – this is a True/false input. If true, it clears any values in the select control on the page before creating the new list. If false, it does not clear the list. Normally, this should be “true”
‘data’ can be an array of single values such as:
['AL','MA','TX','VA']
When the list is created the display value and the saved value will be the same. This would be equivalent to:
<select name="states">
<option value="AL">AL</option>
<option value="MA">MA</option>
<option value="TX">TX</option>
<option value="VA">VA</option>
</select>
However, it is often desired to show one value, but select another. The saved value may be a state code, but the display may be the full state name. If the an entry in nthe array is itself an array, then the first value in the array will be the displayed text, and the second will be the returned value. The following array would create the equivalent select options listed below:
[['Alabama','AL'],['Massachusetts','MA'],['Texas','TX'],['Virginia','VA']]
<select name="states">
<option value="AL">Alabama</option>
<option value="MA">Massachusetts</option>
<option value="TX">Texas</option>
<option value="VA">Virginia</option>
</select>
The full code to set a SELECT with an ID of "Bill_State" to a VALUE of "MA" using the list of states above, and removing any old entries from the SELECT would be:
A5.form.populateSelect('Bill_State','MA',[['Alabama','AL'],['Massachusetts','MA'],['Texas','TX'],['Virginia','VA']],true);
It is often desirable to make a call back to a server side page to return some value or action, and there is no need to actually submit a form element. The A5.ajax.callback() function allows sending values back to a page for processing.
There are two required parameters.
1. ‘url' - the URL of the .a5w page that will handle the callback
2. ‘data’ – The value pairs to send back to the page. These are the values that would be seen after the “?” in a URL, commonly referred to as the GET or query string. This parameter should have the same syntax as any GET.
For example, a common need is to send a couple values back to the page to tell the page that some action must be taken and there are some values available for that action. The URL is the callback page, and the data includes any values to meet that need. In the section on A5.form.submit(), the code snippet for the callback page included a variable ‘action’. While this could be any name, it was used in the ‘if..else’ to determine what code action to take. That code action may or may not need any additional values for the xbasic on the page.
Example:
A code page named “calculatesale.a5w” contains some Xbasic code to populate a control named ‘salestax’. To do this, it needs to be told to run that code section, and send along a value for state to determine what tax table to use. The call back function call could be:
A5.ajax.callback('calculatesale.a5w','action=gettaxtable&state='+$gvs('state_ID'))
In this example, the state value was in a control with an ID attribute of ‘state_ID’. The function $gvs() is a function the core.js Javascript library to harvest the value in the control. It is similar to document.getElementById(), but will harvest a value from any control by ID or name.
The page “calculatesale.a5w” may have some code similar to:
dim __formAction as c = default ""
dim action as c
if __formAction = "Submit" then
if onFormValidate(local_variables())
afterFormValidate(local_variables())
end if
else if __formAction = "Initialize" then
onFormInitialize(local_variables())
else if action = ˛gettaxtable˛
gettax_table(local_variables())
end if
function gettax_table as l(vars as p)
with vars
if eval_valid(˛state˛) = .f. then ' the state value was not sent
'can’t evaluate, quit
exit function
else if state = ˛˛
'state has no value, can’t evaluate, quit
exit function
end if
' ok, all values known - do something
end with
end function
This is a Javascript version of the standard Alpha Five function urlEncode() and is used to encode text so that it can be safely used as part of a URL.
This function can be used when creating a string of data to be passed back to the server by A5.ajax.callback(). It makes sure that both the value name, and value have been URL encoded. The 'value' can either be a single value, or an array of values, allowing you to send back an array to the server.
Example
A5.ajax.buildURLParam('value','my&text');
/* returns: 'value=my%26text'*/
A5.ajax.buildURLParam('value[]',['my&text','another value in the array']);
/* returns: 'value[]=my%26text&value[]=another value in the array'*/
This fuction can be used to display a message box in the HTML that is done entirely in Javascript and HTML meaning that you can present the user with a customized HTML message. The 'title' contains the title HTML text to display on the message box. 'html' contains the HTML to display in the body of the message box. The 'type' is a flag to tell the message box what buttons to display. The values for this flag are:
The 'onClose' argument is a Javascript function that will be called when the user closes the message box. This function will be passed a string containing the value of the button the user pressed ("ok", "yes", "no", or "cancel"). ed ("ok", "yes", "no", or "cancel").
Example
A5.msgBox.show('Save','Do you wish to save.','ync',function(button){
if(button == 'yes'){
// code to save...
} else if(button == 'no'){
// code to close without saving...
}
);