1

I want to make a live preview of input elements in HTML with the JavaScript. Like when use will write something in the field, it will automatically print the text under the field. So how can I make it? I have tried to make it in different ways. But every time I got undefined.

const showCase = document.querySelector('#Message')
const field = document.querySelector('#Field')

field.addEventListener('keyup', () => {
  field.addEventListener('keypress', () => {
    showCase.innerHTML = this.value
  })
})
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
DevR
  • 29
  • 5
  • 1
    Don't use an arrow function (which use the surrounding context's `this`), and stick with a single event listener, rather than nesting. – Heretic Monkey Jan 26 '21 at 16:35

3 Answers3

0

You can try something like below.

const myInput = document.getElementById('input'); // Input Element with id="input" const myOutput = document.getElementById('output'); // An empty paragraph with id="output"
function handleInputKeypress(e) {
  myOutput.textContent = e.target.value;
}

myInput.addEventListener('keyup', handleInputKeypress);
0
const showCase = document.querySelector('#Message')
const field = document.querySelector('#Field')

// Listen for input event
field.addEventListener('input', e => {
    showCase.innerText = e.target.value
})
Gustavo Shigueo
  • 399
  • 3
  • 11
  • 1
    Thank you so much :)) for answering. I really apreciate that. – DevR Jan 27 '21 at 04:15
  • 1
    You're welcome, glad to help :). Also, heads up! If you can, use `.innerText` instead of `.innerHTML` as the latter can be a big security concern because it allows people to write actual HTML tags (including the ` – Gustavo Shigueo Jan 27 '21 at 21:15
  • 1
    oh got it thank you so much – DevR Jan 28 '21 at 05:13
0

try this:

const showCase = document.querySelector('#Message')
const field = document.querySelector('#Field')

field.addEventListener('input', (e) => {
 showCase.innerHTML=e.target.value
})
<p id="Message"></p>
<input id="Field" type="text"/>
Elvis
  • 75
  • 6