Convert Labels to Inputs while preserving Value

0

I would like to know how, within a table I can change the labels of a particular tr (with several td, each with its label), without deleting the table and keeping the value of the labels.

-I've been testing with innerHTML, but it replaces the table ...

<script>
function change(){
var valor = document.querySelector("label").innerHTML;
document.querySelector("td").innerHTML = '<input type="text" value="' + valor + '"/>';
      
        

</script>
<table>
  <tr>
  <td><label>Label Ejemplo</label></td>
  <td><button type="button" onclick="change();">Cambiar a input</button></td>
  </tr>
  <tr>
  <td><label>Label Ejemplo1</label></td>
  <td><button type="button" onclick="change();">Cambiar a input</button></td>
  </tr>
  <tr>
  <td><label>Label Ejemplo2</label></td>
  <td><button type="button" onclick="change();">Cambiar a input</button></td>
  </tr>
 
    
asked by Iron Man 16.04.2018 в 12:01
source

1 answer

0

You can save the value of the label in a variable by clicking on the button and change all the content of the td by an input with that variable.

   <table>
      <tr>
      <td><label>Label Ejemplo</label></td>
      </tr>
    </table>
     <button type="button" onclick="change();">Cambiar a input</button> 

Your table is missing the close tag, keep it in mind or it will give you errors.

Since I do not know whether or not you have more code or how it is, I've taken the tags with querySelector but you can use id or class so that you do not have problems:

function change() {
var valor = document.querySelector("label").innerHTML;

document.querySelector("td").innerHTML = '<input type="text" value="' + valor + '"/>';
}
    
answered by 16.04.2018 / 12:15
source