How can I take the value of a field from a table and add it to an input by clicking on this field

0

Greetings, I would like you to click on a field of a table as an example <tr><td>Juan</td><tr> a text field will take this same value, you could help me thank you very much

    
asked by Juan David 24.06.2016 в 20:57
source

3 answers

1

Because of the scant information you have provided this is something similar to what you are looking for, using jQuery instead of pure javascript.

$(document).ready(function(){
    $(".name").click(function(){ // Al hacer clic en la función
        var value = $(this).text(); // Obtengo el valor del texto cliqueado
        $('#miinput').val(value); // Seteo el valor en el campo de texto
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <a href="#" class="name">Juan<a>
  </td>
  <td>
    <a href="#" class="name">Pedro<a>
  </td>
  <td>
    <a href="#" class="name">Susana<a>
  </td>
</tr>  
<br />
<input id="miinput" />
    
answered by 24.06.2016 / 21:58
source
1

Here is an example of what you are looking for.

var a = document.querySelectorAll("table td"); //Buscamos todos los td que exitan en las tablas
if(a != undefined || a != null){ //Verificamos que si existan
  for(var b in a){ //Iteramos el array: a
    var c = a[b]; //Obtenemos el TD de la iteracion
    if(typeof c == "object"){ //Obtenemos solo los objetos
      c.onclick = function (){ //Asignamos el evento Click
        var tbl = document.querySelector("table"); //Buscamos la tabla
        tbl.insertAdjacentHTML('afterend','<p>'+this.outerText+'</p>'); //Insertarmos despues de la tabla el texto que hemos recuperado del TD
      }
    }
  }
}
<table>
<tr><td>campo a</td><td>campo b</td></tr>
</table>

It may be necessary to adapt it to your particular needs.

    
answered by 24.06.2016 в 21:25
1

What I understood is that you want to click on a <td> its value is displayed in a textbox ( <input /> ).

var nameTxt = document.getElementById('txt-nombre');
var peopleTbl = document.getElementById('tbl-personas');
var cells = peopleTbl.querySelectorAll('tbody td');
cells.forEach(function(cell) {
 
  cell.onclick = function() {
    nameTxt.value = this.innerText;
  };
});
<table id="tbl-personas">
  <thead>
    <tr>
      <th>#</th>
      <th>Nombre</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Luis Sánchez</td>
    </tr>
  </tbody>
</table>
<input type="text" id="txt-nombre" />
    
answered by 24.06.2016 в 22:32