comp.lang.javascript FAQ - Quick Answers 2009-03-02
- From: "FAQ server" <javascript@xxxxxxxxxxxxxx>
- Date: Mon, 02 Mar 2009 09:00:02 +0000
comp.lang.javascript FAQ - Quick Answers- 11, Updated January 26, 2009
1 Meta-FAQ meta-questions
1.1 _Which newsgroups deal with javascript_?
1.2 _What questions are on-topic for comp.lang.javascript_?
1.3 _What should I do before posting to comp.lang.javascript_?
1.4 _Why was my post not answered_?
You are reading the _comp.lang.javascript_ meta-FAQ,
version 11. It is available on the web at
<URL: http://www.jibbering.com/faq/index.html > in HTML form.
This FAQ provides URLs to further information about ECMAScript
(loosely called javascript), and some hints and tips to make your
stay in comp.lang.javascript more enjoyable.
This document was created for three reasons: to help reduce the
high levels of noise on c.l.js, to provide a resource for people
new to javascript, and to point to locations that contain
valuable javascript resources.
Each day, one section of the FAQ is posted for review and questions,
and as a reminder that the FAQ is available.
For additional explanation and detail relating to some aspects
of the FAQ, please see the
FAQ Notes <URL: http://www.jibbering.com/faq/faq_notes/faq_notes.html >.
It has been provided separately to avoid increasing the size of
the FAQ to a point where it would be unreasonable to post it to
the group.
2 Language Overview
2.1 _What is ECMAScript_?
2.2 _What is JScript_?
2.3 _What are object models_?
2.4 _What is the document object model_?
2.5 _Internationalisation and Multinationalisation in javascript.
2.6 _What does the future hold for ECMAScript_?
3 Javascript Resources
3.1 _What books are recommended for javascript_?
3.2 _What online resources are available_?
4 Dates
4.1 _How do I format a date with javascript_?
A date can be formatted to a common ISO 8601 format with:-
/** Get IS0 8601 format YYYY-MM-DD from a Date Object */
function formatDate(date){
var year = padString(date.getFullYear() + "", 4, "0"),
month = padString(date.getMonth() + 1 + "", 2, "0"),
dayOfMonth = padString(date.getDate() + "", 2, "0");
return year + "-" + month + "-" + dayOfMonth;
}
/**
* @param {string} s : input to prefixed.
* @param {number} size : desired length of output.
* @param {string} ch : single character to prefix to s.
*/
function padString(s, size, ch) {
while (s.length < size) {
s = ch + s;
}
return s;
}
Never use a local date/time for a non-local event. Instead, use UTC,
as in ISO 8601 YYYY-MM-DDThh:mm:ssZ (Z is the only letter suffix).
For a local date/time with time offset, to unambiguously indicate a
particular instant, use ISO 8601 format YYYY-MM-DDThh:mm:ss±hh:mm.
<URL: http://jibbering.com/faq/#onlineResources >
<URL: http://en.wikipedia.org/wiki/ISO_8601 >
<URL: http://isotc.iso.org/livelink/livelink/4021199/ISO_8601_2004_E.zip?func=doc.Fetch&nodeid=4021199 >
<URL: http://www.merlyn.demon.co.uk/js-date9.htm >
5 Numbers
5.1 _How do I format a Number as a String with exactly 2 decimal places_?
When formatting money for example, to format 6.57634 to
6.58, 6.5 to 6.50, and 6 to 6.00?
Rounding of x.xx5 is uncertain, as such numbers are not
represented exactly. See also:
Why does simple decimal arithmetic give strange results? <URL: #binaryNumbers >n = Math.round( n * 100)/100 converts n to a Number value
close to a multiple of 0.01. However, there are some problems.
Converting the number to a string (n + ""), does not give
trailing zeroes. Rounding numbers that are very close to x.5, for example,
Math.round(.49999999999999992) results 1.
ECMAScript Ed. 3.0 introduced Number.prototype.toFixed.
There are bugs in JScript's implementation with certain numbers,
for example 0.07.
Function numberToFixed returns accurate results that are
consistent across implementations where n > 0.
var numberToFixed;
(function() {
numberToFixed = toFixedString;
function toFixedString(n, digits) {
var unsigned = toUnsignedString(Math.abs(n), digits);
return (n &< 0 ? "-" : "") + unsigned;
}
function toUnsignedString(n, digits) {
var t, s = Math.round(n * Math.pow(10, digits)) + "",
start, end;
if (/\D/.test(s)) {
return "" + n;
}
s = padString(s, 1 + digits, "0");
start = s.substring(0, t = (s.length - digits));
end = s.substring(t);
if(end) {
end = "." + end;
}
return start + end; // avoid "0."
}
// Test results
var d = document;
d.writeln(" numberToFixed(9e-3, 12) => " + numberToFixed(9e-3, 12));
d.writeln(" numberToFixed(1.255, 2) => " + numberToFixed(1.255, 2));
d.writeln(" numberToFixed(1.355, 2) => " + numberToFixed(1.355, 2));
d.writeln(" numberToFixed(.1255, 3) => " + numberToFixed(.1255, 3));
d.writeln(" numberToFixed(.07, 2) => " + numberToFixed(.07, 2));
d.writeln(" numberToFixed(0.0000000006, 0) => " + numberToFixed(0.0000000006, 1));
d.writeln(" numberToFixed(0.0000000006, 0) => " + numberToFixed(0.0000000006, 0));
})();
Function padString can be found in the answer to:
How do I format a date with javascript? <URL: http://jibbering.com/faq/#formatDate >
<URL: http://www.merlyn.demon.co.uk/js-round.htm >
<URL: http://msdn2.microsoft.com/en-us/library/sstyff0z.aspx >
5.2 _Why does simple decimal arithmetic give strange results_?
For example, 5 * 1.015 does not give exactly
5.075 and 0.06+0.01 does
not give exactly 0.07 in javascript.
ECMAScript numbers are represented in binary as IEEE-754 (IEC 559)
Doubles, with a resolution of 53 bits, giving an accuracy of
15-16 decimal digits; integers up to just over 9e15 are
precise, but few decimal fractions are. Given this, arithmetic
is as exact as possible, but no more. Operations on integers
are exact if the true result and all intermediates are integers
within that range.
In particular, non-integer results should not normally be
compared for equality; and non-integer computed results
commonly need rounding; see How do I format a Number as a String with exactly 2 decimal places? <URL: #formatNumber >
<URL: http://msdn2.microsoft.com/en-us/library/7wkd9z69.aspx >
<URL: http://www.merlyn.demon.co.uk/js-misc0.htm#DW4 >
Otherwise, use Math.round on the results of expressions which
should be of integer value.
5.3 _Why does K = parseInt('09') set K to 0_?
Method parseInt generally needs a
second parameter, radix, for the base (value between 2 and 36).
If radix is omitted, the base is determined by the contents of
the string. Any string beginning with '0x' or '0X' represents a
hexadecimal number. A string beginning with a leading 0 may be
parsed as octal (octal digits are 0-7). The string '09'
is converted to 0.
To force use of a particular base, use the radix
parameter: parseInt("09", base).
<URL: http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/parseInt >
<URL: http://msdn2.microsoft.com/en-us/library/x53yedee.aspx >
<URL: http://docs.sun.com/source/816-6408-10/toplev.htm#1064173 >
<URL: http://www.jibbering.com/faq/faq_notes/faq_notes.html#FAQN4_12 >
5.4 _Why does 1+1 equal 11_? or How do I convert a string to a number?
Variables are not typed; their values are. The conversion between a
string and a number happens automatically. Since plus (+) is
also used as in string concatenation, '1' + 1 is equal to '11'.
The string determines what + does. To overcome this, first convert the
string to a number. For example: +varname or Number(varname) or
parseInt(varname, 10) or parseFloat(varname).
Form control values are strings, as is the result from a prompt
dialog. Convert these to numbers before performing addition by using
the unary + operator: +'1' + 1 result is 2.
Additional Notes:
<URL: http://www.jibbering.com/faq/faq_notes/type_convert.html >
<URL: http://msdn2.microsoft.com/en-us/library/67defydd.aspx >
5.5 _How do I generate a random integer from 1 to N_?
Math.random() returns a value R such that 0 <= R < 1.0; therefore:
// positive integer expected
function getRandomNumber(j) {
return Math.floor(j * Math.random());
}
- gives an evenly distributed random integer in the range from
0 to j - 1 inclusive; use getRandomNumber(n)+1 for 1 to n.
<URL: http://msdn2.microsoft.com/en-us/library/41336409.aspx >
<URL: http://docs.sun.com/source/816-6408-10/math.htm >
How to Deal and Shuffle, see in:
<URL: http://www.merlyn.demon.co.uk/js-randm.htm >
6 Objects
6.1 _When should I use eval_?
6.2 _How do I access a property of an object using a string_?
7 Strings and RegExp
7.1 _How do I trim whitespace_?
8 DOM and Forms
8.1 _How do I get the value of a form control_?
8.2 _My element is named myselect[], how do I access it_?
8.3 _Why doesn't the global variable "divId" always refer to the element with id="divId"_?
8.4 _Why are my rollovers so slow_?
8.5 _How do I disable the right mouse button_?
8.6 _How do I detect Opera/Netscape/IE_?
8.7 _How do I modify the content of the current page_?
8.8 _I get an error when trying to access an element by getElementById but
I know it is in the document. What is wrong_?
8.9 _How can I see in javascript if a web browser accepts cookies_?
9 Windows and Frames
9.1 _How can I disable the back button in a web browser_?
9.2 _How do I communicate between frames in a web browser_?
9.3 _How do I find the size of the window_?
9.4 _How do I check to see if a child window is open, before opening another_?
9.5 _Why does framename.print() not print the correct frame in IE_?
9.6 _How do I close a window and why does it not work on the first one_?
9.7 _Why do I get permission denied when accessing a frame/window_?
9.8 _How do I make a 10 second delay_?
9.9 _How do I change print settings for window.print()_?
9.10 _How do I change the confirm box to say yes/no or default to cancel_?
9.11 _How do I change the text in the url/location bar_?
9.12 _How do I prompt a "Save As" dialog for an accepted mime type_?
9.13 _I have window.status="Moomin"; why doesn't the statusbar change_?
9.14 _How do I modify the current browser window_?
9.15 _How do I POST a form to a new window_?
9.16 _How do I open a new window with javascript_?
10 Ajax and Server Communication
10.1 _What is Ajax_?
10.2 _How do I download a page to a variable_?
10.3 _How do I get a jsp/php variable into client-side javascript_?
10.4 _How do I log-out a user when they leave my site_?
10.5 _How do I run a server side script_?
10.6 _How do I force a reload from the server/prevent caching_?
10.7 _Why is my Ajax page not updated properly when using an HTTP GET request in Internet Explorer_?
11 Debugging
11.1 _How do I get my browser to report javascript errors_?
12 Things not to attempt in a browser
12.1 _How can I prevent access to a web page by using javascript_?
12.2 _How do I protect my javascript code_?
12.3 _How can I access the client-side filesystem_?
12.4 _I have <a href="javascript:somefunction()"> what ... _?
13 Comments and Suggestions
13.1 _Why do some posts have <FAQENTRY> in them_?
13.2 _How do I make a suggestion_?
1_Meta-FAQ meta-questions_
see <URL: http://jibbering.com/faq/#FAQ1 >
Or Wednesdays FAQ posting.
2_Language Overview_
see <URL: http://jibbering.com/faq/#FAQ2 >
Or Wednesdays FAQ posting.
3_Javascript Resources_
see <URL: http://jibbering.com/faq/#FAQ3 >
Or Wednesdays FAQ posting.
4_Dates_
4.1 *How do I format a date with javascript?*
5_Numbers_
5.1 *How do I format a Number as a String with exactly 2 decimal places?*
5.2 *Why does simple decimal arithmetic give strange results?*
5.3 *Why does K = parseInt('09') set K to 0?*
5.4 *Why does 1+1 equal 11? or How do I convert a string to a number?*
5.5 *How do I generate a random integer from 1 to N?*
6_Objects_
see <URL: http://jibbering.com/faq/#FAQ6 >
Or Wednesdays FAQ posting.
7_Strings and RegExp_
see <URL: http://jibbering.com/faq/#FAQ7 >
Or Wednesdays FAQ posting.
8_DOM and Forms_
see <URL: http://jibbering.com/faq/#FAQ8 >
Or Wednesdays FAQ posting.
9_Windows and Frames_
see <URL: http://jibbering.com/faq/#FAQ9 >
Or Wednesdays FAQ posting.
10_Ajax and Server Communication_
see <URL: http://jibbering.com/faq/#FAQ10 >
Or Wednesdays FAQ posting.
11_Debugging_
see <URL: http://jibbering.com/faq/#FAQ11 >
Or Wednesdays FAQ posting.
12_Things not to attempt in a browser_
see <URL: http://jibbering.com/faq/#FAQ12 >
Or Wednesdays FAQ posting.
13_Comments and Suggestions_
see <URL: http://jibbering.com/faq/#FAQ13 >
Or Wednesdays FAQ posting.
.
- Prev by Date: Re: Validation Output: 2 Errors
- Next by Date: Re: Desktop app built with javascript
- Previous by thread: Re: Validation Output: 2 Errors
- Next by thread: Events: How to find out whether default action is prevented?
- Index(es):