0

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";
}
asked Sep 25, 2012 at 16:40

2 Answers 2

2

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.)

answered Sep 25, 2012 at 16:44
Sign up to request clarification or add additional context in comments.

Comments

2

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.)

answered Sep 25, 2012 at 16:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.