Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

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

}
like image 434
ghie Avatar asked Sep 29 '12 13:09

ghie


People also ask

How innerHTML works in JavaScript?

The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags. The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.

How do I write HTML code in innerHTML?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

Where can I use innerHTML?

Use innerHTML when you're setting text inside of an HTML tag like an anchor tag, paragraph tag, span, div, or textarea.

Can you += innerHTML?

Appending to innerHTML is not supported: Usually, += is used for appending in JavaScript. But on appending to an Html tag using innerHTML, the whole tag is re-parsed.


Video Answer


2 Answers

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.

like image 138
David G Avatar answered Oct 19 '22 09:10

David G


Try this:

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

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

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

}
</script>
<body>
<input type="text" id="first" value="good">
<button onclick="displayResult();">Click me!!!</button>
<div id="content"></div>
</body>
like image 39
suresh.g Avatar answered Oct 19 '22 09:10

suresh.g