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";
}

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

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

Comments

Your Answer

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.