0

A small Javascript function to capitalize the contents of a text fields is as follows:

<html>
<head>
<title>capitalize</title>
</head>

<body>
<input type="text" id="uname" length="20" /><br />
<input type="submit" id="submit" value="submit" />
<script>
document.getElementById("submit").addEventListener("click",eve);
function eve(){
    var uname = document.getElementById("uname").value; 
    uname = uname.toUpperCase();
    document.getElementById("uname").value=uname;
}
</script>
</body>

</html>

Now, this is working normally, but when I change the location of the Javascript code to head tag, it's not working.

<html>
<head>
<title>key events</title>
<script>
document.getElementById("submit").addEventListener("click",eve);
function eve(){
    var uname = document.getElementById("uname").value; 
    uname = uname.toUpperCase();
    document.getElementById("uname").value=uname;
}
</script>
</head>

<body>
<input type="text" id="uname" length="20" /><br />
<input type="submit" id="submit" value="submit" />

</body>

</html>
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Pradeep
  • 1,163
  • 6
  • 22
  • 43

4 Answers4

1

Use a document.ready function.

When you put the code before closing the body tag, the DOM has been completely created. Different case when you put it inside the head tag

Enrico
  • 408
  • 6
  • 13
1

Scripts located within the head are executed before the body has been rendered. So the elements you're trying to target don't exist yet.

fridge_light
  • 436
  • 1
  • 3
  • 7
1

Try wrapping js referencing element within window.onload event handler where js is within head element; as the #submit element is not loaded into DOM when .addEventListener attached to document.getElementById("submit")

<html>

<head>
  <title>key events</title>
  <script>
    window.onload = function() {
      document.getElementById("submit").addEventListener("click", eve);

      function eve() {
        var uname = document.getElementById("uname").value;
        uname = uname.toUpperCase();
        document.getElementById("uname").value = uname;
      }
    }
  </script>
</head>

<body>
  <input type="text" id="uname" length="20" />
  <br />
  <input type="submit" id="submit" value="submit" />

</body>

</html>
guest271314
  • 1
  • 12
  • 91
  • 170
1

When in the head, your script executes before the rest of the page is loaded. Make sure you wait for your page to be loaded :

window.onload = function() {
    document.getElementById("submit").addEventListener("click",eve);
    function eve(){
        var uname = document.getElementById("uname").value; 
        uname = uname.toUpperCase();
        document.getElementById("uname").value=uname;
    }    
}
Phil-R
  • 2,183
  • 17
  • 20