简体   繁体   中英

how to fix input from being returned backwards

For some reason when enter input its being returned in reverse. I can get it to work using a for loop, but how would I do this using a while loop?

 var input = document.getElementById('userinput').value;
 var i  = input.length;
 while (i--) {

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

  }

Either reverse the loop counter and condition:

var input = document.getElementById('userinput').value;
var i = 0;
while (i < input.length) {
  document.getElementById('message').innerHTML += input[i] + "<br/>";
}

Or reverse the order of concatenation inside the loop:

var input = document.getElementById('userinput').value;
var i  = input.length;
while (i--) {
  document.getElementById('message').innerHTML =
          input[i] + "<br/>" + document.getElementById('message').innerHTML;
}

Note that either way you shouldn't update .innerHTML in a loop: as a general principle try to minimise DOM updates, so use a temporary variable to build up the desired string and then assign .innerHTML once after the loop. Or for what you're actually doing here you don't need a loop:

var input = document.getElementById('userinput').value;
document.getElementById('message').innerHTML = input.split("").join("<br>");

Simplest way to achieve your goal:

var input = document.getElementById('userinput').value;
document.getElementById('message').innerHTML += input.split('').join('<br/>')

Here's a different approach using split and forEach

var input = document.querySelector("#userinput").value;
var html = "";

input.split("").forEach(function(char){

  html += char + "<br>";

});

document.querySelector("#message").innerHTML = html;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM