/    Sign up×
Community /Pin to ProfileBookmark

Debugging Javascript

Maybe I’m preaching to the choir. So choir, listen up!

I have seen many posts on this forum that say the script is ‘not working’. Many times the problem is simply a syntax or spelling error. (Missing this or that, or ‘object expected’). 9 times out of 10, the browser will point you to the offending line and you can easily fix the problem.

Is your browser set up to give to you an error message?

IE:
In the status bar you might see a ‘warning’ icon. Double-click and you will get details of the error. While you are at it, check the ‘Always display this message…..’ when debugging.
If there’s no popup message, go to:
Tools::Internet Options::Advanced and, in the Browsing options,
check ‘Display a notification about every script error’.

Netscape & Mozilla:
If the script does not do what you expect, type ‘javascript:’, including the :, (no space) in the address bar and details of your error will be displayed.

[code=php]
<html><head><title>untitled</title>
<script type=”text/javascript”>
<!–
Here’s a simple script but it does NOT work!
function gettotals() {
var qty = document.theform.quantity.value;
var price = document.theform.priced.value;
document.theform.total = qty * price;
}
//–>
</script>
</head>

<body>
<form name=”theform” action=”” onsubmit=”return getTotals()”>
<ul><li><input name=”quantity” type=”text” value=12></li>
<li><input name=”price” type=”text” value=11></li>
<li><input name=”total” type=”text”></li>
<li><input type=”submit” value=”Get Total”></li></ul>
</body>
</html>[/code]

This little script has several problems all easily found with the debug tools.
Line 4: ‘Unterminated string constant’. Should be commented out using //
Line 15: ‘Object expected’. Spelling error – javascript is CASE SENSITIVE
Line 7: ‘document.theform.priced.value is null or not an object’. Another spelling error
Line 8: ‘Object doesn’t support this property or method’. Missing the .value

I fixed all the errors and is STILL does not work. Very strange!
You need to ‘return false’ in your function. Otherwise the form will be submitted and return a new page.
(which, in this case, is this page)

to post a comment
JavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@JonaSep 11.2004 — [font=trebuchet ms]I vote [i]sticky![/i] Great post, Nedals. Thanks. ? [/font]
Copy linkTweet thisAlerts:
@steelersfan88Sep 11.2004 — Very nice post. I will add my comments on the same topic, but before wil lsay what I feel is additive to your post, so I will not repeat. And I too think this deserves some notice here in this forum for the time being anyway. Maybe some people will learn.

Users and "Newbies"/"Noobies" seem to think the nickname allows them to make errors, and it is expected that we will answer the question of debug my script:[code=php]
<!-- THREE STEPS TO INSTALL HOW LONG:

1. Copy the coding into the HEAD of your HTML document
2. Add the onLoad event handler into the BODY tag
3. Put the last coding into the BODY of your HTML document -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original: Paul Hartmann ([email protected]) -->
<!-- Web Site: http://www.guycroft.clara.net/ -->

<!-- Begin
function howLong(yr, mo, dy) { //Parameters are calendar Year,Month,Day
var moFlag = 0;
var dyFlag = 0;
var dy = frm.day.value;
var mo = frm.month.value;
var yr = frm.year.value;
var nDate = new Date(); // current date (local)
var nowTime = nDate.getTime(); // current time (UTC)
var thenTime = Date.UTC(yr, mo-1, dy); // specified time (UTC)
var thisYear = nDate.getFullYear();
var thisMonth = nDate.getMonth();
var thisDay = nDate.getDate();
if (isNaN(dy) || isNaN(mo) || isNaN(yr)) {
window.alert("That is not a valid date. Numbers only, please.");
frm.day.focus();
return false
}
if (dy<1 || dy>31) {
window.alert("Day "+dy+" of Month "+mo+" is not a valid date");
frm.day.focus();
return false
} else {
dyFlag=1;
}
if (dy>30 && (mo == 2 || mo==4 || mo==6 || mo==9 || mo==11)) {
window.alert("Day "+dy+" of Month "+mo+" is not a valid date");
frm.day.focus();
return false
} else {
dyFlag=1;
}
if (dy>29 && mo==2) {
window.alert("Day "+dy+" of Month "+mo+" is not a valid date");
frm.day.focus();
return false
} else {
dyFlag=1;
}
if ((mo == 2 && dy == 29) && ((yr%4 != 0) || (yr%100 == 0 && yr%400 != 0))) {
window.alert("29th of February is not a valid date in "+yr);
frm.day.focus();
return false
} else {
dyFlag=1;
}
if (mo<1 || mo>12) {
window.alert("Day "+dy+" of Month "+mo+" is not a valid date");
frm.month.focus();
return false
} else {
moFlag=1;
}
if (dyFlag==1 && moFlag==1) {
if (nowTime >= thenTime) { //-----------------Past or present time
if ((thisMonth > mo-1) || ((thisMonth == mo-1) && (thisDay >= dy))) {
whYrs = thisYear - yr;
spareDys = parseInt((nowTime - Date.UTC(thisYear,mo-1,dy))/(3600000*24));
if ((mo == 2 && dy == 29) && ((thisYear%4 != 0) || (thisYear%100 == 0 && thisYear%400 != 0))) {spareDys = spareDys + 1}
} else {
whYrs = thisYear - yr - 1;
spareDys = parseInt((nowTime - Date.UTC(thisYear-1,mo-1,dy))/(3600000*24));
if ((mo == 2 && dy == 29) && ((thisYear-1)%4 != 0) || ((thisYear-1)%100 == 0 && (thisYear-1)%400 != 0))) {spareDys = spareDys + 1}
}
} else { //----------------------------Future time
if ((thisMonth < mo-1) || ((thisMonth == mo-1)&& (thisDay <= dy))) {
whYrs = yr - thisYear;
spareDys = parseInt((thenTime - Date.UTC(yr,thisMonth,thisDay))/(3600000*24));
if ((thisMonth == 1 && thisDay == 29) && ((yr%4 != 0) || (yr%100 == 0 && yr%400 != 0))) {spareDys = spareDys - 1}
} else {
whYrs = yr - thisYear - 1;
spareDys = parseInt((thenTime - Date.UTC(yr-1,thisMonth,thisDay)) /(3600000*24));
if ((thisMonth == 1 && thisDay == 29) && (((yr-1)%4 != 0) || ((yr-1)%100 == 0 && (yr-1)%400 != 0))) {spareDys = spareDys - 1};
}
}
}
if (nowTime >= thenTime) {
frm.timeBetween.value = "It is "+whYrs +
(whYrs == 1 ? " Year and " : " Years and ") + spareDys +
(spareDys == 1 ? " Day " : " Days ") + "since then"
} else {
frm.timeBetween.value = "It is "+whYrs +
(whYrs == 1 ? " Year and " : " Years and ") + spareDys +
(spareDys == 1 ? " Day " : " Days ") + "until then"
}
}
// End -->
</script>

</HEAD>

<!-- STEP TWO: Insert the onLoad event handler into your BODY tag -->

<BODY onLoad="frm.day.focus()">

<!-- STEP THREE: Copy this code into the BODY of your HTML document -->

<div align="center">
<h2>Time Until or Since</h2>
Figure out how long in years and days between <b>Today</b> and any <b>Other Date</b>.<br>
[Usual Gregorian calendar assumed<br>
Century years are leap years only if divisible by 400.]
</div>
<div align="center">
<form name="frm" action="GET" onreset="frm.day.focus()">
Enter a date — <b>Day, Month and Year</b> — in numbers:<br>
(January=01, ... December=12)<br>
dd mm yyyy<br>
<input type="Text" name="day" value="" maxlength="2" size="2">
<input type="Text" name="month" value="" maxlength="2" size="2">
<input type="Text" name="year" value="" maxlength="4" size="4">
<br>
<input type="Button" name="Calc" value="Calculate How Long" onclick="howLong(year,month,day)">
<br>
<input type="text" name="timeBetween" size="40">
<br>
<input type="RESET" value="Clear">
</form>
</div>


<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size: 5.06 KB -->[/code]
(Script from JS Source, one error added [well removed])

The easy thing to do is exactly what Nedals presented. Getthe line number and the problem. Common errors include:

> object expected ... you missed something, such as the property you wish to change

> ??? is undefined ... you probably misspelled ???

> Expected "#" ... you probably are missing a brace or parenthesis, or have added an extra. Normally extras result in the # being a semicolon (the code line separator).


If worse comes to worse, and you don't find the problem ... guess what, we probably can. But don't handicap us. Give us the error message you received. Maybe the browser you are using as well.

A total newbie should not have trouble replacing [font=monospace]vlaue[/font] with [font=monospace]value[/font], if an error is received. Nor should they have trouble replacing [font=monospace]aelrt("Hi"[/font] with [font=monospace]alert("Hi")[/font].

Great post.
Copy linkTweet thisAlerts:
@David_HarrisonSep 11.2004 — Good posts guys, I should also add that if I come accross someone using a script from [url=http://www.javascriptsource.com]javascriptsource.com[/url] and needs help debugging/adding to it I will just re-write it.

Reason? Well listen up everyone!

[color=red][SIZE=3]Scripts from [url=http://www.javascriptsource.com]javascriptsource.com[/url] inherently suck!!![/SIZE][/color]

All scripts that I've seen so far from there fall into one or more of these categories:

  • * tacky

  • * buggy

  • * browser dependant (usually IE only)

  • * inaccessible (pretty much 100% of the scripts from there fall into this one)
  • Copy linkTweet thisAlerts:
    @steelersfan88Sep 11.2004 — [i]Originally posted by lavalamp [/i]

    [B][color=red][SIZE=3]Scripts from [url=http://www.javascriptsource.com]javascriptsource.com[/url] inherently suck!!![/SIZE][/color][/B][/QUOTE]
    That isn't very nice ... but very, very true. It is a fact that all of these sites get submitted code from visitors. And sites like http://javascripts.com and A1 Javascripts, and HotScripts are all the same way (although HotScripts PHP and others aren't bad ... because the lnaguage is supportedly the same on all browsers).

    Requiting them is the exact thing that is need to be done. The only significance at all the the javascript source, it allows users that want scripts similar to those on the JS Source to explain better what they want.

    If a website were a person, you should never treat it with such awful garbage of code (as I provided up above). That is like treating a child the trash.
    Copy linkTweet thisAlerts:
    @printelectricSep 16.2004 — Hey everybody. I realize this is an old post, but great info. Thanks. The nifty "javascript:" debugging trick is great. I'm a Mac guy, and my site gets lots of traffic from other Mac people. I'm wondering if anyone has any tricks for beating Javascript debug info out of Safari.

    I'm running into a problem with a script that runs great in Mozilla, but not quite so great in Safari. I suspect it makes use of some event handling features that aren't supported in Safari, but I'm finding it very difficult to check internal variables. I already have a trace function which works fine, but it would be nice to be able to pull up the full list of active variables and check things...

    The very basic root of my problem is this (no pun) -

    someImage.onload = myFunction;

    function myFunction() {

    trace(this.src);

    }

    In Mozilla, this.src yields the src of someImage within myFunction. In Safari, it's undef. If you don't have any debugging advice, then maybe someone has a clever way to pass the someImage variable to myFunction? I've tried just passing it -

    someImage.onload = myFunction(someImage);

    function myFunction(theImage) {

    trace(theImage.src);

    }

    When I do this, the event handler/function call fails, as far as I can tell.


    TIA -

    Scott
    Copy linkTweet thisAlerts:
    @JonaSep 16.2004 — [font=trebuchet ms][i]Note to Moderators: This thread should probably be split.[/i]

    Scott, did you define the [/font][font=courier new]trace()[/font][font=trebuchet ms] function?[/font]
    Copy linkTweet thisAlerts:
    @javaNoobieSep 16.2004 — This should be a sticky
    Copy linkTweet thisAlerts:
    @printelectricSep 16.2004 — Yes - didn't include because that's been working on all browsers just fine, but here is in case anyone wants it:

    function trace(msg) {

    if ((w == null) || (w.closed)) {

    w = window.open("","traceWindow","width=300,height=800,status=yes,resizable=yes");

    w.moveTo(950,25);

    }

    w.document.write(msg + "<br>");

    }

    This is a slight mod. of a trace function that I picked up from another post, I think.
    Copy linkTweet thisAlerts:
    @printelectricSep 16.2004 — My last post was cut off - to continue...

    I'm almost certain the problem is not in my trace function, as this has been working NP.

    The problem is that when I call a function from an event handler like this:

    someImage.onload = myFunction;

    The keyword "this" is undef. within myFunction, while in other browsers, the keyword "this" is a reference to the image (or whatever) on which the event handler is defined.

    Thanks again for your help.

  • - Scott
  • Copy linkTweet thisAlerts:
    @HaganeNoKokoroSep 16.2004 — The cleverest way I've ever been able to pass an object to a function like that is to pass its id, then use document.getElementById. But hopefully there's someone smarter than me in here.
    Copy linkTweet thisAlerts:
    @printelectricSep 16.2004 — That's a good idea. If you have any code you could post, or even just outline, would be much appreciated. I'll try anything at this point.

    Thanks,

    Scott
    Copy linkTweet thisAlerts:
    @HaganeNoKokoroSep 16.2004 — Here, this should demonstrate it:
    <i>
    </i>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN"
    "http://www.w3.org/TR/html4/strict.dtd"&gt;

    &lt;html&gt;
    &lt;head&gt;
    &lt;title&gt;Function Example&lt;/title&gt;
    &lt;META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"&gt;
    &lt;script type="text/javascript"&gt;

    //function that writes an image to the page and sets up the onload handler for it.
    function init() {
    document.write("&lt;img id='someImage_id' src='http://www.google.ca/intl/en_ca/images/logo.gif'/&gt;");
    var someImage=document.getElementById('someImage_id');
    someImage.onload=myFunction('someImage_id');
    }

    var w=null;
    function trace(msg) {
    if ((w == null) || (w.closed)) {
    w = window.open("","traceWindow","width=300,height=800,status=yes,resizable=yes");
    w.moveTo(950,25);
    }
    w.document.write(msg + "&lt;br&gt;");
    }

    function myFunction(id) {
    var obj = document.getElementById(id);
    trace(obj.src);
    }

    init();

    &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
    &lt;div&gt;&lt;/div&gt;
    &lt;/body&gt;
    &lt;/html&gt;
    Copy linkTweet thisAlerts:
    @HaganeNoKokoroSep 16.2004 — oops that one turns out to work in IE but give errors in Netscape. This one gives no errors but only works in Netscape. Guess this is trickier than I thought...
    <i>
    </i>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN"
    "http://www.w3.org/TR/html4/strict.dtd"&gt;

    &lt;html&gt;
    &lt;head&gt;
    &lt;title&gt;Function Example&lt;/title&gt;
    &lt;META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"&gt;
    &lt;script type="text/javascript"&gt;
    var w=null;
    function trace(msg) {
    if ((w == null) || (w.closed)) {
    w = window.open("","traceWindow","width=300,height=800,status=yes,resizable=yes");
    w.moveTo(950,25);
    }
    w.document.write(msg + "&lt;br&gt;");
    }

    function myFunction(id) {
    var obj = document.getElementById(id);
    trace(obj.src);
    }

    function init() {
    var someImage=document.createElement("IMG");
    document.body.appendChild(someImage);
    someImage.setAttribute("src", "http://www.google.ca/intl/en-ca/images/logo.gif");
    someImage.setAttribute("id", "someImage_id");
    someImage.setAttribute("onload", "myFunction('someImage_id')");

    var someOtherImage=document.createElement("IMG");
    document.body.appendChild(someOtherImage);
    someOtherImage.setAttribute("src", "http://www.google.ca/intl/en-us/images/logo.gif");
    someOtherImage.setAttribute("id", "someOtherImage_id");
    someOtherImage.setAttribute("onload", "myFunction('someOtherImage_id')");
    }

    &lt;/script&gt;
    &lt;/head&gt;
    &lt;body onload="init()"&gt;
    &lt;div&gt;
    &lt;/div&gt;
    &lt;/body&gt;
    &lt;/html&gt;
    Copy linkTweet thisAlerts:
    @JonaSep 16.2004 — [font=trebuchet ms]Perhaps Safari doesn't support the onLoad event of an image. Tell me if you get an error when running this script:[/font]

    <i>
    </i>&lt;script type="text/javascript"&gt;&lt;!--
    var myImage = new Image();
    myImage.src = "files/file.gif";
    myImage.onload = function() {alert("Hi.")};
    //--&gt;&lt;/script&gt;
    Copy linkTweet thisAlerts:
    @printelectricSep 16.2004 — Safari works fine with image.onload. The problem is with this particular event handler format assignment syntax:

    image.onload = someFunction;

    In theory, the keyword 'this' within the function someFunction should be a reference to the object on which the event handler was defined, in this case "image".

    I've just tested in several browsers - here are my results:

    Mac Mozilla - no problem

    Mac Netscape 7.0 - no problem

    Mac IE 5.2 (which we just call "Exploder") -

    The event handler works fine, the window resize code does not - no problem, I can find a workaround.

    XP IEv6.0.2900 blah blah - Works fine if you turn off the pop-up blocker, so I'll have to find a work around for that. I would think that this would be considered a "requested" pop-up, but oh well.

    Safari - Event handler/function call does not work at all as far as I can tell.

    Here is a link to the test site.

    http://www.printelectric.com/dev/pages/print.php

    The code that I'm working on executes when you click on the main image at the left side of the screen. Much appreciate any help guys. Please feel free to yank any code you might like.

    Also, sorry so stupid, but Javanoobie - what is a sticky?
    Copy linkTweet thisAlerts:
    @JonaSep 16.2004 — [font=trebuchet ms]I'm on Windows; does Safari at least give the error message? Try the following...[/font]

    <i>
    </i>someImage.onload = function(){ trace(this); }
    Copy linkTweet thisAlerts:
    @printelectricSep 16.2004 — When I run the following in Safari, the trace window opens, but there is nothing at all written to it, which I assume to mean that "this" is either undef. or null.

    In Mozilla, the trace yields:

    "[object HTMLImageElement]"

    Which is just what you would expect...

    Not that it matters, but yes I do actually have an image titled "unknown.jpg" in the folder with my test file.

    <script>

    var w = null;

    function trace(msg)

    {

    if ((w == null) || (w.closed)) {

    w = window.open("","traceWindow","width=300,height=800,status=yes,resizable=yes");

    w.moveTo(950,25);

    }

    w.document.write(msg + "<br>");

    }

    var someImage = new Image;

    someImage.onload = function(){ trace(this); }

    someImage.src = "unknown.jpg";

    </script>
    Copy linkTweet thisAlerts:
    @HaganeNoKokoroSep 16.2004 — maybe a combination of mine and Jona's?
    <i>
    </i>var w = null;

    function trace(msg)
    {
    if ((w == null) || (w.closed)) {
    w = window.open("","traceWindow","width=300,height=800,status=yes,resizable=yes");
    w.moveTo(950,25);
    }
    w.document.write(msg + "&lt;br&gt;");
    }

    var someImage = new Image;
    someImage.id="someImage_id";
    someImage.onload = function(){ trace(document.getElementById('someImage_id').src); }
    someImage.src = "unknown.jpg";
    ×

    Success!

    Help @Nedals spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.19,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...