How to send data from a php loop to an input using JS

3
How to send a data from a loop in php where each input will be able to be sent to another input that is outside of the php loop, I'm trying in javascript. I get the data directly from the database. Remembering that the input name goes outside and is what gets the value.

function passar(){ 
var valorA = document.getElementById("valorA"); 
var nome = document.getElementById("nome"); 
nome.value = valorA.value; 
}; 
<?php
         $sql_lista = mysql_query("SELECT*FROM login LIMIT 0, 2"); 
		  //aqui fazemos a contagem para exibição se caso ouver dados(quantidade)
		 $sql_contar = mysql_num_rows($sql_lista);
		 		 ?>

  <?php
     while($resultado = mysql_fetch_array($sql_lista)){ ?>    

<?php echo $resultado['usuario'];?>
 
    <form>

<INPUT TYPE="text" SIZE="3" name="valorA" id="valorA" value="<?php echo $resultado['lo_id'];?>"></input>
 
<button type="button" onclick="passar();"> passar valores </button> 

   
 </form>
        
  <?php
  //fechamos o while
		 } 
  ?>
 Nome:<input type="text" id="nome" size="10"/> 
    
asked by anonymous 27.01.2016 / 16:17

1 answer

2

The ID attribute of an element must be unique. You should then change the id of the elements within the while, so that each is given a unique id.

It can be solved like this:

<input 
    TYPE="text" 
    SIZE="3" 
    name="valorA" 
    id="valorA_<?=$resultado['lo_id'] ?>" 
    value="<?php echo $resultado['lo_id'];?>" 
/>

Remembering that <input> does not exist closing tag and should be closed like this:

<input... />

In the button you pass the id as a parameter

<button type="button" onclick="passar(<?=$resultado['lo_id']?>);"> passar valores </button> 

And your js function will look like this:

function passar(id){ 
    var valorA = document.getElementById("valorA"+id); 
    var nome = document.getElementById("nome"); 
    nome.value = valorA.value; 
}; 

I hope I have helped!

    
27.01.2016 / 17:31