0

I am a beginner coder and I am having trouble with a simple program that basically says whatever you type into a text box under/above it. For example, if you type "Hello World" into the box, it will say "Hello World" in a paragraph under/above it. My current (faulty) code is this:

<p id="test"></p>
<input id="ipone type="text">
<script>
var x = document.getElementById("ipone").value;
x = test;
document.getElementById("test").innerHTML= document.getElementById("ipone").value;
</script>

I am trying to get it to work, and I am trying to have it as simple and small as possible. Please help.

arhak
  • 2,488
  • 1
  • 24
  • 38
Komali
  • 77
  • 10
  • 1
    The reason why this doesn't work is because the script is being called immediately. You don't actually get a chance to type something in and change the text so it just takes the blank input and doesn't run again. What the answer does is call a function when the input changes so the javascript doesn't run until the text has been changed. – L_Church Feb 02 '18 at 13:57

3 Answers3

2

The event you need is oninput, which triggers on any text typing, pasting, cutting, etc. by the user.

var input = document.getElementById("ipone");
var paragraph = document.getElementById("test");

input.addEventListener("input", function() {
  var value = input.value;
  paragraph.innerText = value;
});
/* just for demonstration */
#test{
  min-height: 20px;
}
<p id="test"></p>
<input id="ipone" type="text">
Lucas
  • 413
  • 1
  • 7
  • 15
1

I have wrapped your code into a function, and called that function whenever the input changes

more on the topic: Best way to track onchange as-you-type in input type="text"?

<p id="test"></p>
<input id="ipone" type="text" onchange="update()" onkeypress="update()" />
<script>
function update() {
    var txt = document.getElementById("ipone").value;
    document.getElementById("test").innerHTML= txt;
}
</script>
arhak
  • 2,488
  • 1
  • 24
  • 38
0

<input type="text" id="txtDemo" onchange="myFunction()"/>
<p>Entered Text:<span id="value"></span> </p>
<script>
 function myFunction(){
  var inputValue=document.getElementById("txtDemo").value; 
  var p=document.getElementById("value")
  p.innerHTML=inputValue;
 }
</script>

This code may help you

Abhishek
  • 972
  • 3
  • 12
  • 24