Click here to Skip to main content
15,359,445 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have been practicing javascript and i am not able to display the value .It keeps showing null.

What I have tried:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
 
</head>
<body>
 
    <h1>testing dom </h1>
        name <input type="text">
        number <input type="number" id="number" value="000">
        <button onclick="clicked()">submit</button>
        

  

   
    <script>
        
        function clicked()
        {
            document.write("submit clicked");
            var a = document.getElementById("number").value;
            document.write(a);
         
        }
</script>
</body>
</html>
Posted
Updated 19-May-22 18:56pm

Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.
Your first call to document.write clears the document, so there is no element to find.

Either read the value before calling document.write:
JavaScript
function clicked()
{
    var a = document.getElementById("number").value;
    document.write("submit clicked");
    document.write(a);
}
or display the output in some other way - eg: in the developer console[^]:
JavaScript
function clicked()
{
    console.log("submit clicked");
    var a = document.getElementById("number").value;
    console.log(a);
}
   
Document.Write clears the existing HTML and replaces it with a blank page.
So when you call it to display "submit clicked" the subsequent call to getElementById fails because the HTML no longer contains and such element.

Try this:
JavaScript
function clicked()
{
    var a = document.getElementById("number").value;
    document.write("submit clicked");
    document.write(a);
}
   
I think your example code is incorrect, the first call to document.write rewrites the entire page so the next line in your script does not find an element with the id "number". If you remove that line it will (sort of) work. However, I would suggest working through the JavaScript Tutorial[^] for better samples.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900