Mithrandir
Mithrandir

Reputation: 59

Each input letter is returned on individual line

As the title suggests, I want each letter enter into the input field to be displayed on a new line using a while loop. For example if someone enters 'cat' in the input box this would be returned:

c

a

t

This is what I have so far, but at the moment its only displaying the first letter.

 var input = document.getElementById('userinput').value;
  var i  = input.length;
  while (i--) {
    document.getElementById('message').innerHTML = (input[i]);
  }

Upvotes: 1

Views: 38

Answers (1)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

The line:

document.getElementById('message').innerHTML = (input[i]);

Is completely overwriting the HTML of the #message element, so it will only have the value of the last iteration. Instead you will want do:

document.getElementById('message').innerHTML += (input[i]) + "<br />";

With the <br /> moving to a new line. To have it in a top-down fashion you may want to use a normal for-loop instead:

for(var i = 0; i < input.length; i++)
    document.getElementById('message').innerHTML += input[i] + "<br />";

Below is a basic snippet example (hitting enter or unfocusing will trigger the event):

document.getElementById('text').addEventListener("change", function(){
  document.getElementById('message').innerHTML = "";
  input = document.getElementById('text').value;
  for(var i = 0; i < input.length; i++)
      document.getElementById('message').innerHTML += input[i] + "<br />";
});
<input id="text" type="text" />
<div id="message"></div>

Upvotes: 2

Related Questions