Reverse order of names in inputs?

1

I'm trying to do an exercise where I have to get 5 names in 5 different input, store them in an array and print them in the same fields but in the reverse order 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];
    }
}
    
asked by anonymous 01.09.2015 / 03:36

2 answers

0

Here is a 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>
    
01.09.2015 / 03:55
2

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

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

See the program working: link

    
01.09.2015 / 03:51