0

For example, I have some function:

var inputA = document.getElementById("A").value;
var inputB = document.getElementById("B").value;
document.write("First input is: " + inputA + '<br />');
document.write("Second input is: " + inputB + '<br />');

So, in this case I use document.write(), but with several these functions it gets messed up. This document.write() overwrites my parent html page. How to set it up to open in a new page/tab. Or how to use document.close() in this situation in order to work properly.

Should I use some better method, which will also have the same functionality as this one. I want to set up a variable that will print a line of text, code, numbers etc. in the desired position of a page.

mpavlovic89
  • 749
  • 3
  • 16
  • 37
  • 3
    Use some container element and `innerHTML`. – Sirko Feb 23 '14 at 14:23
  • @Quentin - that is not a really good dupe candidate... The answers there are all using only jQuery and don't really address the issue. – Lix Feb 23 '14 at 14:27

3 Answers3

3

Instead of overwriting your whole page you should just update parts of it, for example.

<div id="myDiv">
</div>

<script>
  document.getElementById("myDiv").innerHTML = ("First input is: " + inputA + '<br />');
</script>
htatche
  • 693
  • 3
  • 17
2

What you will be able to do is to place that text in a specific element rather than just writing it to the document.

Assuming you have this in your HTML:

<div id="content" />

You can use something like this:

var str = "This is the content";
var elem = document.getElementById("content");
elem.innerHTML = str;

If all you are worried about is debugging your logic, you could always just use a console.log() to print something out to the JS console so you can take a look at it.

Lix
  • 47,311
  • 12
  • 103
  • 131
2

Use innerHTML

<input type="text" id="A" value="some" />
<input type="text" id="B" value="other value" />
<div id="result"></div>

<script type="text/javascript">

var inputA = document.getElementById("A").value;
var inputB = document.getElementById("B").value;

var firstInput = "First input is: " + inputA + '<br />';
var secondInput = "First input is: " + inputB + '<br />';

document.getElementById("result").innerHTML = firstInput + secondInput;
</script>

DEMO

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34