JavaScript FAQ

Ask me no questions and I’ll tell you no lies.

As this list becomes more comprehensive, we will try to add some order to it.

FAQ Topics


Strings and numbers

Q: How do I convert a string to a number?
A: You use parseInt(stringInstnace) or parseFloat(stringInstance)

Example:

var a = “5″;            //this is a string, not a number
var b = parseInt(a);    //this converts the string into a number
var c = a + a;          //c will be a string with the value “55″;
var d = b + b;          //d will be a number with the value 10;

alert(”c: ” + c + “nd: ” + d);

Q: How do I format a number so it only has N decimal places?
A: By using the .toFixed(N) method of the Number? object.

Example:

var num = 3.324234
alert(num.toFixed(2));  //will return 3.32

Q: Why does stringObj.replace("someString", "replacementString"); only replace the first occurrence of "someString"?
A: Becaues the first argument for tring.replace method is a Regular Expression? not a string. If you do the following it’ll replace all occurrences of "someString": stringObj.replace(/someString/g, "replacementString");.



Detection

Q: How do I test if Javascript is enabled?
A:The simple answer is that if Javascript is enabled, your code will work, and there is no way to ‘test’ per say. However, you can inform a user who has Javascript disabled by using the noscript tag.

Example:

noscriptThis site requires Javascript and you currently have it dissabled.  noscript

Another way to ensure that your site is only viewed by people that have js enabled, is to have your index page do a redirect to the real page. If they do not have js enabled, the page will not redirect and you can have the index say something like ‘js must be enabled’.

location.href=’realStartPage.htm’;  js not enabled

Q: How do I test if cookies are enabled?
A: By attempting to write a cookie and then reading it.

Example:

var testcookie = ‘jscookietest=valid’;
document.cookie = testcookie;
if (document.cookie.indexOf(testcookie) == -1) {
alert(”You do not have cookies enabled.  This site requires cookies to be enabled.”);}

document.cookie = testcookie + ‘;expires=’ + new Date(0).toGMTString();

Q: How do I test if ActiveX is enabled?
A: By using the following snippet:

var agnt = navigator.userAgent.toLowerCase();
if (agnt.indexOf(’msie’)!= -1 && document.all) {
var control = (agnt.indexOf(’msie 5′) != -1) ? ‘Microsoft.XMLHTTP’ : ‘Msxml2.XMLHTTP’;
try
{new ActiveXObject(control);}
catch (e) {
alert(”You do not have ActiveX enabled.”);
else {
alert(“ActiveX is currently not enabled.  You’re smarter than the average bear.”;}

Q: How do know which browser the client is using?
A: User agent sniffing results in cruddy applications, you should try to use object detection where possible instead. For example, if you want to see whether element.currentStyle (an IE attribute) will be available, don’t try and work out if you’ve got IE, just see if you’ve got element.currentStyle


Forms

Q: Can I submit a form using Javascript?
A: Yes.

Example:

document.formName.submit();

Q: Can I change the action of a form with Javascript?
A: Yes.

Example:

document.formName.action = “somePage.jsp”;

Q: Can I validate a form before submitting it?
A: Yes, by attaching an onsubmit event to the




tag. For more detailed information and examples check out the Form Validation page.Q: How do I itterate through the elements of a form?
A: By looping through the form’s elements array.Example:

var elements = document.formName.elements;

for (var i = 0; i < elements.length; i++) {
alert("element " + i + " name: " + elements[i].name;
}

Q: How do I toggle the readOnly attribute of a fied?
A: By setting the readOnly property to true or false.

Example:

function toggleReadonly(fieldObj) {
if (fieldObj.readOnly)
fieldObj.readOnly = false;
else
fieldObj.readOnly = true;
}


Select Boxes

Q: How can I get the value of a select?
A:

var aSelect = document.formName.selectName;
aSelect.options[aSelect.selectedIndex].value;

Q: How can I get the text from an option?
A:

var aSelect = document.formName.selectName;
aSelect.options[aSelect.selectedIndex].text;

Q: How can I assign a value to a select?
A:

var aSelect = document.formName.selectName;
for (var i = 0; i < aSelect .options.length; i++)
if (aSelect.options[i].value == 1) aSelect.options[i].selected = true;

Q: How do I add options to a select?
A: By using the Option object.

Example:

var aSelect = document.formName.selectName;

aSelect.options[aSelect.options.length] = new Option(”Name 1″,”1″);
aSelect.options[aSelect.options.length] = new Option(”Name 2″,”2″);
aSelect.options[aSelect.options.length] = new Option(”Name 3″,”3″);

Q: How can I flush the options in a select?
A: By setting its options length to zero.

document.formName.selectName.options.length = 0;

Q: How can I unselect a selected item in a listbox?
A:

document.formName.selectName.selectedIndex = -1;


Dates

Q: How do I get the current date and time?
A: By using the Date() object.

Example:

alert(new Date());

Q: How do I get information about a different date or time?
A: By using the new Date() constructor as passing any of the following arguments in order year, month, day, hours, minutes, seconds, miliseconds. Note, you may omit any of these except for year and month.

Example:

var oldDate = new Date(1999, 11, 31);
alert(oldDate);

Q: How do I get the current day of the month?
A: By using the getDate() or getUTCDate() method. It will return a value between 1 and 31.

Example:

var today = new Date();
alert(today.getDate());

Q: How do I get the current day of the week?
A: By using the getDay() or getUTCDay() method. It will return a value between 0 (Sunday) and 6 (Saturday).

Example:

var today = new Date();
alert(today.getDay());

Q: How do I get the current month?
A: By using the getMonth() or getUTCMonth() method. It will return a value between 0 (January) and 11 (December).

Example:

var today = new Date();
alert(today.getMonth());

Q: How do I get the current year?
A: By using the getFullYear() or getUTCFullYear() method. It will return the year in YYYY format.

Example:

var today = new Date();
alert(today.getFullYear());

Q: How do I get the current time?
A: By using the getHours(), getMinutes() and getSeconds() methods or their UTC equivalents.

Example:

var today = new Date();
alert(today.getHours() + “:” + today.getMinutes());


Dimensions

Q: How do I get the resolution (width/height) of the screen?
A: By using the screen object. You can use the width and height properties to get the width and height of the screen, and you can also use the more useful availWidth and availHeight properties to get the actual available width and height that take into consideration things such as the taskbar , MSN or other toolbars.

Example:

//display the screen resolution
alert(”Your resolution: ” + screen.width + ” x ” + screen.height);

//display the available screen size
alert(”Your available resolution: ” + screen.availWidth + ” x ” + screen.availHeight);

Q: How do I get the size of a browser window?
A: By using document.body.clientWidth and document.body.clientHeight. Note that you can only call these events once the page has loaded.

Q: How do I get the width/height of an element?
A: By using offsetWidth and and offsetHeight.

Example:

var obj = document.getElementById(’someDiv’);
alert(”width: ” + obj.offsetWidth + “nheight: ” + obj.offsetHeight);


Positioning

Q: How do I find out a HTML element’s coordinates? (x y position)?
A: Set the element’s style.position to either 'relative', 'absolute' or 'fixed', then read offsetTop and offsetLeft

Example:

var e = document.getElementById(”some_id”);
e.style.position = “relative”;  // only needs to be done once
alert(e.offsetTop);

Q: How do I move the scrollbar to a specific position? (x y position)?
A: By using the window’s scrollTo() method.

Example:

function moveToTop() {
self.scrollTo(0,0);
}


Misc

Q: How can I make a new window / popup?
A: First, ask yourself is a popup really necessary? Also, realize that nearly all the browsers now have some form of popup blocking software built in. If you still really want to use a popup, then I suggest you appy the logic found in this Metalusions article.
Q: How can I get values from the query string (url)?
A: This function will return you the corresponding value based on whatever key you pass it as a parameter:

function getParameter(param) {
var temp = location.search.split(param + "=");
if (temp.length > 1) {
return temp[1].split("&")[0];}
else {
return "";}
}

Q: How do I apply MD4, MD5 or SHA-1 using Javascript?
A: Without a doubt, the best reference for cryptography, MD4, MD5 and SHA-1 for Javascript can be found at Paul Andrew Johnston’s home page.

He provides working examples, complete source code (under the BSD license) and has great info on how to set up a Challenge Hash Authentication login system (CHAP) which is possibly the safest way to use a password login without using SSL. His site makes MD5 really easy to understand, and his code is used by such big sites such as Yahoo! Mail.

Q: How do I get all the names of attributes of an object?
A:

for (foo in someObj) {
alert(foo);
}

Q: How do I something regarding Java?
A: Javascript is not Java. Do not try to use it like Java. If you want to do Java things, use Java.

Q: What is client-side scripting?
A: Client-side scripting is the use of scripts that are interpreted by a web browser client. These scripts are used to modify the appearance and/or content of a web page dynamically. By far the most widely used scripting language for client-side scripting is Javascript, but there are several other scripting languages that may be used, such as VBScript, Python, and Ruby. It is called client-side scripting because the entire script is run on the client’s computer, within their web browser. It typically does not interact with the web server directly. HTML forms are the most common method of passing information from the client to the server, and client-side scripting can be used to manipulate such forms.

Q: How do I stop the image toolbar from IE from showing up when I mouse over an image?
A: Insert the following into your header: