JavaScript | Very Frequently Asked Questions
How do you check if a date is valid?
<script language="JavaScript"><!--
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
function isDate (day,month,year) {
// checks if date passed is valid
// will accept dates in following format:
// isDate(dd,mm,ccyy), or
// isDate(dd,mm) - which defaults to the current year, or
// isDate(dd) - which defaults to the current month and year.
// Note, if passed the month must be between 1 and 12, and the
// year in ccyy format.
var today = new Date();
year = ((!year) ? y2k(today.getYear()):year);
month = ((!month) ? today.getMonth():month-1);
if (!day) return false
var test = new Date(year,month,day);
if ( (y2k(test.getYear()) == year) &&
(month == test.getMonth()) &&
(day == test.getDate()) )
return true;
else
return false
}
if (isDate(31,2,1997))
document.write("Valid");
else
document.write("Invalid");
//--></script>
How can I calculate the number of days elapsed between two dates?
<script language="JavaScript"><!--
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
function daysElapsed(date1,date2) {
var difference =
Date.UTC(y2k(date1.getYear()),date1.getMonth(),date1.getDate(),0,0,0)
- Date.UTC(y2k(date2.getYear()),date2.getMonth(),date2.getDate(),0,0,0);
return difference/1000/60/60/24;
}
document.write(daysElapsed(new Date(2000,0,1),new Date(1999,11,31)));
//--></script>
How do you round a number to a X decimal places?
<script language="JavaScript"><!--
function round(number,X) {
// rounds number to X decimal places, defaults to 2
X = (!X ? 2 : X);
return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}
document.write(round(1,2)+'<BR>');
document.write(round(1.2,2)+'<BR>');
document.write(round(1.23,2)+'<BR>');
document.write(round(1.234,2)+'<BR>');
document.write(round(1.2345)+'<BR>');
//--></script>
Is it possible to output a number e.g. 1234567 as 1,234,567?
<script language="JavaScript"><!--
function outputComma(number) {
number = '' + number
if (number.length > 3) {
var mod = number.length%3;
var output = (mod > 0 ? (number.substring(0,mod)) : '');
for (i=0 ; i < Math.floor(number.length/3) ; i++) {
if ((mod ==0) && (i ==0))
output+= number.substring(mod+3*i,mod+3*i+3);
else
output+= ',' + number.substring(mod+3*i,mod+3*i+3);
}
return (output);
}
else return number;
}
document.write(outputComma(1)+'<br>');
document.write(outputComma(12)+'<br>');
document.write(outputComma(123)+'<br>');
document.write(outputComma(1234)+'<br>');
document.write(outputComma(12345)+'<br>');
document.write(outputComma(123456)+'<br>');
document.write(outputComma(1234567)+'<br>');
document.write(outputComma(12345678)+'<br>');
document.write(outputComma(123456789)+'<br>');
document.write(outputComma(1234567890)+'<br>');
//--></script>
Another solution is given below:
<script language="JavaScript"><!--
function reverseIt(str) {
if (!str) return; // nothing to change
var rstr = '';
for (i=str.length-1;i>=0;i--) rstr += str.charAt(i);
return rstr;
}
function thousands(str) {
var saveStr = "" + str;
if (saveStr.length < 4) return str;
var revStr = reverseIt(saveStr);
var newStr = '';
for (var i=0;i<revStr.length;i++) {
if (i>0 && (i%3)==0) newStr += ',';
newStr += revStr.charAt(i);
}
return reverseIt(newStr);
}
//--></script>
<form>
<input type="text" name="inText">
<input type="text" name="outText">
<input type="button"
onClick="this.form.outText.value=thousands(this.form.inText.value);"
value="thousands">
</form>
How do I make a button that when clicked displays a message in a field?
<form name="formName" onSubmit="return functionName();">
<input type=text name="textName">
<input type=submit value="Display">
</form>
<script language="JavaScript"><!--
function functionName() {
window.document.formName.textName.value = 'hello world';
return false;
}
//--></script>
How do I set and access the value of a hidden form field?
<form name="anotherName">
<input type=hidden name="hiddenName" value="initial">
</form>
<script language="JavaScript"><!--
document.write(document.anotherName.hiddenName.value+'<br>');
document.anotherName.hiddenName.value = 'hello world';
document.write(document.anotherName.hiddenName.value+'<br>');
//--></script>
How can I click on a thumbnail in one frame and load the image in another?
First, in the parent.html file:
<frameset cols="120,*">
<frame src="thumb.html" name="thumbFrameName">
<frame src="other.html" name="otherFrameName">
</frameset>
In the thumb.html file:
<script language="JavaScript"><!--
function loadPicture(pictureName) {
parent.otherFrameName.location.href = "other.html?" + pictureName;
}
//--></script>
<a href="JavaScript:loadPicture('big.jpg')"><img
src="small.gif" width=100 height=100 border=0></a>
And finally in the other.html file:
<body bgcolor="#000000">
<center>
<script language="JavaScript"><!--
if (location.search.length > 0) {
document.write("<table height='100%' width='100%'>");
document.write("<tr><td align=center valign=middle>");
document.write("<img src='"+location.search.substring(1)+"'>");
document.write("<\/td><\/tr><\/table>");
}
//--></script>
</center>
</body>
How can I get script embedded in a table to work?
<table border=1>
<tr>
<td>
<script language="JavaScript"><!--
document.write("JavaScript Text which may or may not be output");
//--></script>
</td>
<td>
<script language="JavaScript"><!--
document.write("JavaScript Text which may or may not be output");
//--></script>
</td>
</tr>
</table>
Whereas the following code will work on all:
<script language="JavaScript"><!--
document.write("<table border=1>");
document.write("<tr>");
document.write("<td>");
document.write("JavaScript Text which may or may not be output");
document.write("<\/td>");
document.write("<td>");
document.write("JavaScript Text which may or may not be output");
document.write("<\/td>");
document.write("<\/tr>");
document.write("<\/table>");
//--></script>
How can I password protect a page?
The simplist and most effective password protection using just
clientside JavaScripting, relies on the user not knowing the target
filename:
<script language="JavaScript"><!--
function go() {
window.location.href = "http://www.somewhere.com/" +
document.formName.passwordName.value + '.html';
return false;
}
//--></script>
<form name="formName" onSubmit="return go()">
Enter Password: <input type="password" name="passwordName" value="" size=8>
</form>
Note, the user can find the directory location, by examining the
source, therefore you must protect your directory by placing a default
file inside it, which your server will always send when the directory
is requested, e.g. index.html, otherwise a directory listing will be
sent.
It is also possible on Unix systems, to just set the parent (or
all) directory's permissions to rwx--x--x and all other files to
rwxr--r--. The user cannot get directory listings, but can still
access any files there. (Thanks to
Mike Crawford for this last tip.)
How do I pass a month from a drop down list to a field on another page?
Use the following on the source page:
<form>
<select name="selectName">
<option>January
<option>February
<option>March
<option>April
<option>May
<option>June
<option>July
<option>August
<option>Spetember
<option>October
<option>November
<option>December
</select>
<input type="button" value="Go" onClick="window.location.href = 'nextpage.html?' +
this.form.selectName.options[this.form.selectName.selectedIndex].text">
</form>
And the following on the nextpage.html:
<form name="formName"><input type="text" name="textName"></form>
<script language="JavaScript"><!--
document.formName.textName.value = location.search.substring(1);
//--></script>
Or, alternatively:
<script language="JavaScript"><!--
document.write("<form><input type='text' ");
document.write("value='"+location.search.substring(1)+"'><\/form>");
//--></script>
As this code passes data in the location object's search property, it
does not work offline in Internet Explorer 4.
How can I compare a date in a string with todays date?
<script language="JavaScript"><!--
function isitToday(dateString,dateType) {
/*
function isitToday
parameters: dateString dateType
returns: boolean
dateString is a date passed as a string in the following
formats:
type 1 : 19970529
type 2 : 970529
type 3 : 29/05/1997
type 4 : 29/05/97
dateType is a numeric integer from 1 to 4, representing
the type of dateString passed, as defined above.
Returns true if the date passed is equal to todays date
Returns false if the date passed is NOT equal to todays
date or if dateType is not 1 to 4.
*/
var now = new Date();
var today = new Date(now.getYear(),now.getMonth(),now.getDate());
if (dateType == 1)
var date = new Date(dateString.substring(0,4),
dateString.substring(4,6)-1,
dateString.substring(6,8));
else if (dateType == 2)
var date = new Date(dateString.substring(0,2),
dateString.substring(2,4)-1,
dateString.substring(4,6));
else if (dateType == 3)
var date = new Date(dateString.substring(6,10),
dateString.substring(3,5)-1,
dateString.substring(0,2));
else if (dateType == 4)
var date = new Date(dateString.substring(6,8),
dateString.substring(3,5)-1,
dateString.substring(0,2));
else
return false;
if (date.toString() == today.toString())
return true;
else
return false;
}
if (isitToday("19970529",1)) alert('true'); else alert('false');
if (isitToday("970529",2)) alert('true'); else alert('false');
if (isitToday("29/05/1997",3)) alert('true'); else alert('false');
if (isitToday("02/06/97",4)) alert('true'); else alert('false');
//--></script>
Where are the official online JavaScript documents?
How do I read data from an input file?
There is a way in netscape to do this and I am sure Internet explorer
can also. Below I have code that can read any file on the clients
machine, but only with their approval. This code only works on
Netscape:
<script language="JavaScript"><!--
function readFromFile(filename) {
var text = '';
var filechar;
netscape.security.PrivilegeManager.enablePrivilege('UniversalFileAccess');
var file = new java.io.File(filename);
var FileReader = new java.io.FileReader(file);
filechar = FileReader.read();
while (filechar != -1) {
text = text + String.fromCharCode(filechar);
filechar = FileReader.read();
}
FileReader.close();
return text;
}
alert(readFromFile('test.txt'));
//--></script>
Andre De Bruin writes:
- There is a method to read a file in Netscape Navigator (through the Java class)
- Depending on what you want to do with the file, this me be a solution:
- create a separate (invisible) frame
- use parent.FRAMENAME.location = "yourfile.htm" to load the file in that frame
- The file is loaded, you can not read the lines from within Javascript (but you can read all the hrefs and anchors
- there are no security violations when the file is on the same host (and path?) as the loading file.
- very kinky is to have javascript in that file that is being loaded, code that is activated with an onLoad()
- Even more kinky is to have the loaded file after doing whatever work it needed to do, perform a document.location = "anotherfile.htm" ON ITS OWN FRAME. I used this method to make a search application with "unlimited" data input: the loaded scripts output their data to a common frame.
Can I have a counter without the need for CGI or counter providers?
As you cannot write to a file, then you cannot store a count. The only other
possible option is to store a cookie which holds the number of times the user
has visited your page.
How do you debug JavaScript?
Placing stategic copies of alert() within code can inform you where in a script
you get, e.g. if you place alert("#1") prior to some code, and then alert("#2") after,
then if you never receive the #2 alert message then the problem lies between the two alert()
lines.
Move one or other of the above alert() lines nearer to one another,
until all that remains is one statement. This will then identify the exact failing line.
When using object hierarchy, e.g. document.frame.form.element, if you
don't get the results you expect, add an extra alert() function before the
problem area, e.g. alert(document) or alert(document.frame) or alert(document.frame.form),
this should give you some indication of whether the named object is right for
your purposes.
When using JavaScript to dynamically produced HTML, e.g.
document.write("<p><b><i>bold italics</i></b>")
if the results are not as expected, then replace with:
document.write("<p><b><i>bold italics</i></b>")
or:
document.write("<xmp><p><b><i>bold italics</i></b></xmp>")
Although it looks more complicated, it at least gives you the chance to see exactly what is being generated by the browser.
To find a bug in a complex calculation using numbers or strings, break down the combination, e.g. the following code:
var date = new Date(string1.substring(0,4),string2.substring(4,6)-1,string3.substring(6,8));
Break it up as follows:
var a = string1.substring(0,4);
alert(a);
var b = string2.substring(4,6)-1;
alert(b);
var c = string3.substring(6,8);
alert(c);
var date = new Date(a,b,c);
This gives the ability to check that there are no data or logic errors.
There are also two script debuggers available:
Netscape JavaScript Debugger
http://developer.netscape.com/software/jsdebug.html
Microsoft - Script Debugger for Internet Explorer
http://www.microsoft.com/workshop/prog/scriptie/
The online utility Code
Colorizer allows you to paste your code into a form and then will
color your code so that you can see its structure. Useful if your text
editor does not provide a similar function.
How do I get the *.js files to not display their code in Netscape?
Use JavaScript to output the HTML tags to request an external JavaScript *.js source file wen the browser is not Netscape:
<SCRIPT LANGUAGE="JavaScript"><!--
if (navigator.appName != "Netscape")
document.write('<script src="whatever.js"><\/script>');
//--></SCRIPT>
How do I get the IP address of the visitor?
In Netscape Navigator try the following, which requires Java to be
enabled:
<script language="JavaScript"><!--
if (navigator.appName == 'Netscape' && navigator.javaEnabled()) {
var myAddress = java.net.InetAddress.getLocalHost();
var host = myAddress.getHostName();
var ip = myAddress.getHostAddress();
document.write('hello '+ host + '\n' + ip);
}
//--></script>
In both Internet Explorer and Netscape Navigator try:
<script src="http://jshelper.pharlap.com/utils/ipaddr.js"></script>
<script language="JavaScript"><!--
if (typeof(IPAddr) == 'undefined')
alert('IP Address is unknown');
else
alert('IP Address is ' + IPAddr);
//--></script>
How can I disable the "View Source" menu item?
Sorry, not possible. Its by default and cannot be modified.
Where can I find FAQs for server-side javascript?
Top
|