0

I have a small code trying to append values using HTML inputs to the same document.

<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
<script type="text/javascript">
  var child = document.getElementById("text").value;

  function func() {
    var h = document.getElementById('myh');
    h.insertAdjacentHTML('afterend', '<p> New Para' + toString(child) + '</p>');
  }
</script>

the variable child dose not take the text value from the input, which outputted as `undefined'

image 1: typed Test

enter image description here

Image 2: Clicked the Button

enter image description here

how to get the value form the input as New ParaTest?

Code Edited using the answer.

NIMISHAN
  • 1,265
  • 4
  • 20
  • 29

3 Answers3

1

You don't need toString() method, remove it.

Get the reference of element in the child variable and get the value the func()

var child = document.getElementById("text");

function func() {
  var h = document.getElementById('myh');
  h.insertAdjacentHTML('afterend', '<p> New Para: ' + child.value + '</p>');
}
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

child variable needs to assign inside func function and don't need toString() try this

function func(){
   var h = document.getElementById('myh');
   let child = document.getElementById("text").value;
   h.insertAdjacentHTML('afterend','<p> New Para' + child + '</p>');
}
<html>
<body>
    <h2 id="myh"> Header</h2>
    <input type="text" id="text">
    <button onclick="func()">Append</button>
</body>
</html>
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
1

Your variable should be global. Try taking it inside the function and then check it.

    function func(){
        var child = document.getElementById("text").value;
        var h = document.getElementById('myh');
        h.insertAdjacentHTML('afterend','<p> New Para' + toString(child) + '</p>');
    }
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43