ghie
ghie

Reputation: 587

How can I use innerHTML in JavaScript?

My problem is that I don't know how to show the innerHTML of my form.

The form is like a survey form and once you clicked the submit button, all the contents I had answered would show like a summary page...

function displayResult() {
  var first = document.getElementById("first").value;
  var middle = document.getElementById("middle").value;
  var last = document.getElementById("last").value;
  var maincontent = document.getElementById("content").innerHTML;
  maincontent = "<p>" + first;
}

Upvotes: 12

Views: 75816

Answers (5)

Penny Liu
Penny Liu

Reputation: 17498

Another alternative is to use the setHTML method instead of innerHTML internally. You can check the browser support for setHTML.

function displayResult() {
  const first = document.getElementById("first").value;
  const maincontent = document.getElementById("content")
  maincontent.setHTML("<p>" + first)
}
<input type="text" id="first" value="<p>We <em>had</em> to do something about it.</p>">
<button type="button" onclick="displayResult()">Submit</button>
<div id="content"></div>

Upvotes: 0

suresh gopal
suresh gopal

Reputation: 3156

Try this:

function displayResult() {
  var first = document.getElementById("first").value;

  var maincontent = "";
  maincontent = "<p>" + first + "</p>";
  document.getElementById("content").innerHTML = maincontent;

}
<input type="text" id="first" value="good">
<button onclick="displayResult();">Click me!!!</button>
<div id="content"></div>

But, you should have id as first. and you should need content div in html part.

Upvotes: 5

David G
David G

Reputation: 96855

var maincontent = document.getElementById("content").innerHTML;
maincontent = "<p>" + first;

On the second line you're overwriting the variable, not setting the .innerHTML. This is what you want:

var maincontent = document.getElementById("content");
maincontent.innerHTML = "<p>" + first;

Also, you must make sure the elements with ids of "first" "middle" and "last" actually exist, or this might cause a TypeError.

Upvotes: 11

Quannt
Quannt

Reputation: 2075

What is your element with id "contend" , a div? td? tr? or ? The way it should be is

 <div id='content'> 
   </div>

and then this is the javascript code

document.getElementById("content").innerHTML = "<p>" + first + middle + last + "</p>"

Upvotes: 0

jonvuri
jonvuri

Reputation: 5940

Instead of this:

var maincontent = document.getElementById("content").innerHTML;
maincontent = "<p>" + first;`

Try this:

document.getElementById("content").innerHTML = "<p>" + first;

You may also want to use .innerHTML to get 'first', rather than .value? I'm not sure what kind of element 'first' is.

Upvotes: 0

Related Questions