Search code examples
javascriptecmascript-6template-literals

How to print input from user with template literals in JS? It's giving error


I'm using JS to render HTML code and would like to add user input also in that HTML for this am using template literal but its not working. It says [object HTMLTextAreaElement]

Am using this code.

<script>
function print(){
var heading = document.getElementById("heading") //I have a input tag with id heading in HTML code and type text
open = document.open("")
open.document.write(`
<!DOCTYPE html>
<html>
   <head>
      <title>Dummy Page</title>
   </head>
   <body>
      <div>
         <h1>${heading}</h1>
         // this line is supposed to print user input.
      </div>
   </body>
</html>
}
</script>



Solution

  • The message [object HTMLTextAreaElement] that is printed on the page tells you exactly what the problem is: is that you are attempting to inject a DOM node into a string template.

    What you should be doing is getting the value of the element #heading (since it s a textarea element, it will have the value property), not the DOM node itself. This should work:

    var heading = document.getElementById("heading").value;