3

I have the follwing JavaScript.

<html>
    <head>
        <script language="JavaScript">
            function fdivisible()
            {
                document.write("<h1> Just a javascript demo</h1>");
                var x=document.forms["aaa"]["txt1"].value;  
                alert(x);   
            }
        </script>
    </head>
    <body>
        <form action="#" name="aaa">
            Enter a no. : <input type="text" name="txt1" id="txt1" />
            <input type="button" value="Click" onclick="fdivisible();">
        </form>
    </body>
</html>

The problem is, the first line of the JS function is executing and the rest are ignored. If I comment out the first line the rest of the code is executed. Can anybody explain to me why it is so?

Arvind Lairenjam
  • 981
  • 1
  • 8
  • 14

8 Answers8

7

Because calling document.write implicity calls document.open, which clears the document on which it has been called:

If a document exists in the target, this method clears it

After the call to document.write, the element you're trying to get a reference to no longer exists in the DOM, and an error is thrown. If you look in the error console it should be something along the lines of the following:

TypeError: Cannot read property 'txt1' of undefined

James Allardice
  • 164,175
  • 21
  • 332
  • 312
6

document.write can only be used during the initial loading of the document.

If you want to insert your H1 when the function is called, you may replace

document.write("<h1> Just a javascript demo</h1>");

with

var h1 = document.createElement('h1');
h1.innerHTML = " Just a javascript demo";
document.body.appendChild(h1);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

document.write(content) writes content on the document stream.

You have to close the stream after writing on the document in order to continue the page loading

document.write("hello");
document.close();
tehsis
  • 1,602
  • 2
  • 11
  • 15
1

With addition to dystroy answer, you could replace document.write with:

document.body.innerHTML += '<h1>Javascript demo</h1>
WTK
  • 16,583
  • 6
  • 35
  • 45
1

You're destroying the DOM with your document.write call. In some browsers, this also destroys global variables.

Instead use:

var element = document.createElement('h1');
element.appendChild(document.createTextNode('text'));
document.body.appendChild(element);
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

use document.write() at the end of all JS statements. The script element is never executed after it.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

Try this:

var x=document.getElementById(txt1).value;
alert(x);
SajjadHashmi
  • 3,795
  • 2
  • 19
  • 22
0

You can write to the document with

    document.write("<h1> Just a javascript demo</h1>");

only once and it applies to the whole document. If you want to put you will have to add a class/id to it and then put text in that class/id.

Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79