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

Asked

Viewed 451 times

3

How to send a data from a php loop where each input will be able to be sent to another input that is out of the php loop, I’m trying in javascript. I receive od data directly from the database. Remembering that the name input is outside and is what receives 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"/> 

1 answer

2


The ID attribute of an element must be unique. So you must change the id of the elements inside while, so that each one receives 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> no closing tag should be closed like this:

<input... />

On the button you pass the id as parameter

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

And your function js 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’ve helped!

  • Damn brother ce helped a lot now I’m going to change this code to what I want thanks even, I wasn’t knowing how to do I’m lousy at js. A sim preciso no codigo javascript retirar o valora ficanco assim var valora = Document.getElementById(id);

  • Oops... I’m glad I could help you.

  • another question @Thomas Lima and if I don’t want to get the id type pick up a name, how would I do it?

  • You can use custom attributes: date-title = "My title". Ai in your pass() function would take: var elem = Document.getElementById(id); var title = elem.getattribute('date-title');

Browser other questions tagged

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