pajevic
pajevic

Reputation: 4667

JavaScript function "not defined" after importing jQuery

I have the following (simplified) code:

<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Test</title>

        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" />

        <script language="javascript" type="text/javascript">
            function testFunction() {
                alert('It works');
            }
        </script>
    </head>
    <body>
        <form method="post" action="test.html" onsubmit="testFunction()">
            <input type="submit" value="Test" />
        </form>
    </body>
</html>

My testFunction() function works fine by it self, that is until I import jQuery with the line

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" />

Now it fails and tells me that Uncaught ReferenceError: testFunction is not defined

I am hoping this is a newbie mistake and that I am missing something obvious. Notice that I haven't even try to use jQuery yet.

Upvotes: 2

Views: 1207

Answers (4)

mgibsonbr
mgibsonbr

Reputation: 22007

Despite being valid XML, many HTML elements (such as script, textarea etc) don't work well in most browsers if you close them using a trailing slash (i.e. <element />). You need to create open and close tags for them to work (<element></element>). That seems to be true for XHTML as well.

Others, like your input tag, work fine the way it is. I don't know why some require a closing tag and others not, neither a list of those elements, I just know some of them from experience...

Upvotes: 1

micha
micha

Reputation: 49612

You have to close the script tag in the right way

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

(note the closing </script> tag)

Upvotes: 2

Talha Akbar
Talha Akbar

Reputation: 10040

   <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> // close the script tag properly

        <script type="text/javascript"> // there is no need of writing language="javascript"
            function testFunction() {
                alert('It works');
            }
        </script>

hey man there is no need of writing language="javascript" because type already specifies it!

Upvotes: 1

qwerty
qwerty

Reputation: 5256

You need to close the <script> tag fully.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

Works great on jsfiddle after changing: http://jsfiddle.net/PVYM9/

Also, in HTML5 you can shorten the doctype to just <!DOCTYPE html>, and you don't need to define type properties for your <script> tags. See jsfiddle for example.

Upvotes: 7

Related Questions