Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onKeyUp not working javascript [duplicate]

I am trying to populate the div tag with what is typed in the name field (example below) using javascript. I am not sure what I am doing wrong but it is not working and I have at a loss as to why not? All I want is when the user types their first name it appears below. I have looked at other examples and still confused why this one will not work.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4 /strict.dtd"> 
<html lang="en-GB"> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>hello whirled</title> 
    <script type="text/javascript">
        document.getElementById("name").onkeyup = function() {
            document.getElementById("display").innerHTML = this.value;
        }
    </script> 
</head> 
<body> 
    <h1> 
        Bla Bla
    </h1> 
    <form method="get" action=" "> 
        <p> 
            Other Text goes here
        </p> 
        <p> 
            Type your first name here: 
            <input type="text" id="name" value="">
        </p> 
        <div id="display">'s ball is not in the ball park.</div> 
        <noscript>  
            <div> 
                If you can see this then SCRIPTS are turned OFF on your machine and it won't work 
            </div>   
        </noscript> 
    </form> 
</body> 

like image 946
Dino Avatar asked Jun 18 '26 06:06

Dino


1 Answers

You are referencing the element before it is rendered. It is like trying to eat a pizza before you make it.

You need to attach the event after the element is rendered. Either window.onload, document ready, or add the script after the element in the markup.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4 /strict.dtd"> 
<html lang="en-GB"> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>hello whirled</title>      
</head> 
<body> 
    <h1> 
        Bla Bla
    </h1> 
    <form method="get" action=" "> 
        <p> 
            Other Text goes here
        </p> 
        <p> 
            Type your first name here: 
            <input type="text" id="name" value="">
        </p> 
        <div id="display">'s ball is not in the ball park.</div> 
        <noscript>  
            <div> 
                If you can see this then SCRIPTS are turned OFF on your machine and it won't work 
            </div>   
        </noscript> 
    </form>
    <script type="text/javascript">
        document.getElementById("name").onkeyup = function() {
            document.getElementById("display").innerHTML = this.value;
        }
    </script> 
  </body>
</html> 
like image 196
epascarello Avatar answered Jun 19 '26 19:06

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!