dinners
dinners

Reputation: 25

javascript function call not working

Inside register.js I have a function called username() and I want to call it from my webpage but the function will not run.

Here is where I include the .js file and call the function:

<head>
        <link rel="stylesheet" href="css/base.css" />
        <script src="resources/jquery-1.8.1.min.js"></script>
        <script src="resources/register.js"></script>
        <script type="text/javascript">username();</script>
</head>

This is in the .js file:

function username(){
    document.getElementById("username").innerHTML="Username already in use";
}

Upvotes: 0

Views: 2640

Answers (2)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

This is a common mistake from folks just starting out in Javascript. Trouble is, if you don't know what to call it, it is hard to search for the answer.

What is happening: When the <head> element is processed, nothing in the document body exists yet. Your element username doesn't exist, so the getElementById fails.

Solution 1 Move <script type="text/javascript">username();</script> to just before the </body> so everything will be in place.

Solution 2 Use the onload event to run your Javscript after everything else runs with a

<body onload="username()">

(jQuery has its own onload event handling as well.)

Upvotes: 2

Quentin
Quentin

Reputation: 943569

You have no element with the id username.

(You might have one lower down in the document, which you haven't shared with us, but since you are calling the function directly (and not in response to an event, such as load) while still in the <head> it won't yet exist.)

Upvotes: 2

Related Questions