Common JavaScript Errors

See more about:

Sometimes you can look and look at code, and not see an error. Here’s a list of common errors.

Forgot to load jQuery

Your JS code looks like it’s doing nothing. Check the error console. You might see something like this:

Firefox error console

If you see the message “$ is not defined,” make sure you loaded jQuery, with a statement like this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Missing #

Suppose you have this:

<p id="total">Total: </p>

This is wrong:

$("total").show();

The # is missing. It should be:

$("#total").show();

The #total tells jQuery: “Look for something with an id of total.” Without the #, jQuery doesn’t know what property to look at.

Missing .

Suppose you have this:

<p class="output">Total: </p>
<p class="output">Count: </p>

This is wrong:

$("output").show();

The . is missing. It should be:

$(".output").show();

The .output tells jQuery: “Look for things with a class of output.” There could be more than one. Without the ., jQuery doesn’t know what property to look at.

Confusing # and .

Remember that # works for id. . works for class.

@+@ and parseFloat

The + operator has two meanings in JS: addition, and string concatenation. Enter some numbers below and click the button.

X:

Y:

X+Y:

Enter various things in the fields. See what happens. Try entering 12 and 13. Try some text as well.

Here’s the important code:

x = $("#x").val();
y = $("#y").val();
sum = x + y;

Now try this version:

X:

Y:

X+Y:

Here’s the only difference:

sum = parseFloat(x) + parseFloat(y);

JS will assume that + means concatenate, unless you tell it otherwise. Use parseFloat(x) to tell JS to convert x to a number.

parseFloat(x) lets x be a number with a decimal part, like 3.14. There’s another function, parseInt(), that will strip off everything to the right of the decimal point. So 3.14 would become 3.


Lessons

How to...


Dogs