show the value of the child inputs of Divs js

Asked

Viewed 35 times

0

I need the for/while to show on the screen the string placed in the input of the first div the first time the loop is executed and the second time to show on the screen the string placed in the input of the second div and so on.

<!DOCTYPE html>
<html>
<body>

<div id="cki11" class="ind">
	<input class="in" id="in1" placeholder="Nome do indicado">
</div>
<div id="cki12" class="ind">
	<input class="in" id="in1" placeholder="Nome do indicado">
</div>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var i = 1;
    var x = 2;
    var a = 5;
    var e = 5;
    
    while(i <= x){
    	a = "cki1" + i.toString(); // armazena a string correspondente ao id da div que sera chamada
        e = document.getElementById(a).children[0].value; // pega o valor do input com base no div pai
        document.write(e+"<br>");// exibe o valor do input 
        i++;
    }
    
}
</script>

</body>
</html>

  • I posted an answer, if I have trouble understanding explain how it works;

  • Lucas notices that id="in1" will generate repeated Ids on the page, this is invalid HTML, you must have unique Ids.

  • I hadn’t noticed... Thanks

1 answer

1


Why not just this?

function myFunction() {
    var inputArray =  document.querySelectorAll(".ind input");
    for(let i = 0; i < inputArray.length; i++){
      document.write(inputArray[i].value + '<br>');
    }
}
<div id="cki11" class="ind">
	<input class="in" id="in1" placeholder="Nome do indicado">
</div>
<div id="cki12" class="ind">
	<input class="in" id="in1" placeholder="Nome do indicado">
</div>
<button onclick="myFunction()">Try it</button>

  • 1

    Thank you very much Marconi... it worked!!

Browser other questions tagged

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