Archive for July 22, 2007

JavaScript to Get the Day of the Week

Posted in JavaScript, programming on July 22, 2007 by Joey

The day of the week can be retrieved in JavaScript by using the getDay method JavaScript’s Date object, as follows:

var dteNow = new Date();
var dteToday = dteNow.getDay();
document.write(dteToday);

The value returned by getDay is between 0 (Sunday) and 6 (Saturday). To convert this to a string representing the day of the week, use a switch statement.

var strDay = '';

switch(dteToday)
{
case 0: strDay = 'Sunday'; break;
case 1: strDay = 'Monday'; break;
case 2: strDay = 'Tuesday'; break;
case 3: strDay = 'Wednesday'; break;
case 4: strDay = 'Thursday'; break;
case 5: strDay = 'Friday'; break;
case 6: strDay = 'Saturday'; break;
}

document.write(strDay);

Related articles:
JavaScript Date Object
JavaScript Switch Case Statement Example

JavaScript to Remove Dollars Signs From a Number

Posted in JavaScript, Regular Expressions, Software, programming on July 22, 2007 by Joey

A common problem with HTML input forms is that users tend to include dollars signs when inputting currency numbers. These dollars signs can be easily removed through JavaScript by using the JavaScript replace function and a simple regular expression. This is demonstrated in the following example:

var Amount = '$13.22';
var ReplacedAmount = Amount.replace(/\$/g,'');
document.write(ReplacedAmount);

This example shows a dollar amount that includes a dollar sign. To remove the dollar sign, use the replace function. The first argument to the replace function is a regular expression. This regular expression states that all dollar signs in the Amount variable be found. The replace function then replaces those dollars signs with nothing.

Related articles:
JavaScript Regular Expressions
JavaScript Regular Expression Backslash

Labeling HTML Form Elements

Posted in JavaScript, Software, internet, programming on July 22, 2007 by Joey

The HTML label tag is used to label form elements as follows:

<label for="FirstNameLabel">First Name:</label>
<input type="text" name="FirstName" id="FirstNameLabel">

As seen in this example, the for attribute of the label tag binds it to the id attribute of the input control. Why use the label tag? Browsers handle the text in a label tag in a unique way. When the label text is clicked on, focus is automatically given to the associated form control. This is especially useful in the case of radio buttons and checkboxes, as their text can be clicked to toggle the control. For example:

<input type="radio" name="OnOffControl" id="on">
<label for="on">On</label>
<input type="radio" name="OnOffControl" id="off">
<label for="off">Off</label>

Another compelling reason to use the label tag is that it aids browsers that are built for people with disabilities. An example is speech browsers, which use the label to determine how to describe the form controls.