Invert order of names in inputs?

Asked

Viewed 188 times

1

I am trying to do an exercise where I have to take 5 names in 5 different input, store them in an array and print them in the same fields but in reverse order to what they were.

function inverteNomes(){

    var nome1 = document.getElementById("txtNome0").value;
    var nome2 = document.getElementById("txtNome1").value;
    var nome3 = document.getElementById("txtNome2").value;
    var nome4 = document.getElementById("txtNome3").value;
    var nome5 = document.getElementById("txtNome4").value;

    var arrayNomes = [nome1, nome2, nome3, nome4, nome5];
    var invertido = arrayNomes.reverse();   

    for(var i = 0; i < 5; i++){
        var nome = document.getElementById("txtNome" + i);
        nome.innerHTML = invertido[i];
    }
}
  • Rafael’s answer already points out the problem, here is a suggestion to be more DRY: http://jsfiddle.net/hkco5c00/

2 answers

2

Good evening, your program is not working because you are trying to change the value of an input using the property innerHTML, the right property for this is the value.

for (var i = 0; i < 5; i++) {
  var nome = document.getElementById("txtNome" + i);
  nome.value = invertido[i];
}

See the program working: http://codepen.io/raftelti/pen/VvwWBP?editors=101

0


Following practical example.

<html>
<head>
    <script>
      function inverso(){
        var nome1 = document.getElementById("txtNome0").value;
        var nome2 = document.getElementById("txtNome1").value;
        var nome3 = document.getElementById("txtNome2").value;
        var nome4 = document.getElementById("txtNome3").value;
        var nome5 = document.getElementById("txtNome4").value;

        var arrayNomes = [nome5, nome4, nome3, nome2, nome1];   

        for(var i = 0; i < 5; i++){
            document.getElementById("txtNome"+i+"").value = arrayNomes[i];
        }
    }
    </script> 
</head>
<body>
    <input type="text" id="txtNome0"/><br/>
    <input type="text" id="txtNome1"/><br/>
    <input type="text" id="txtNome2"/><br/>
    <input type="text" id="txtNome3"/><br/>
    <input type="text" id="txtNome4"/><br/><br/>

    <input type="button" value="Inverter" onclick="inverso();"/>
</body>
</html>
  • Rodrigo, I find the other answer better by explaining the problem with text. If you add that to your answer (ie because the AP code didn’t work) I’ll give +1 also in your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.