place table elements in a list

Asked

Viewed 772 times

1

I have an empty table , and then a javascript code that allows you to fill the table through input. What I want is to put all the information of this table in an array (depending on the number of rows and columns in the table) so that later I can eliminate elements in the array and automatically change in the table.

HTML

<input type="text" name="nome" id="nomedisciplina">    
<button onclick="adicionar()">Adicionar disciplina</button><br>

JAVASCRIPT

function adicionar() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    cell1.innerHTML = document.getElementById("nomedisciplina").value;
}

O que pretendo é que apareça na tabela a ordem que aparece na lista

  • Have you ever considered using angular or jquery? will make it too easy what you want to do

  • How would you do in Jquery ?

  • You can explain the part better "fill the table by input"? how would that be in practice? put the array in input and the table be changed? on is this array? in code or text/json?

  • I have an empty table and through the input with id="disciplines" puts this value in the table( table of a column ) , this is the code I already have , now my doubt is how I put the information already present in the table in an array so associate to case later I need to delete in one side delete in another

  • You can better explain what you want to do with this array and how changing the array waits for the table to be changed?

1 answer

2


You can do it like this:

TABLE:

<table id="dataTable">
    <tr>
      <th>Codigo</th>
      <th>Descricao</th>
    </tr>
    <tr>
      <td>1</td>
      <td>José</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Maria</td>
    </tr>
</table>

Javascript:

var table = document.getElementById( "dataTable" );
var tableArr = [];
for ( var i = 1; i < table.rows.length; i++ ) {
    tableArr.push({
        codigo: table.rows[i].cells[0].innerHTML,
        descricao: table.rows[i].cells[1].innerHTML
    });
}
console.log(tableArr);

See the jsFiddle: https://jsfiddle.net/xL6hbxga/

  • It is giving me a problem, with the code I put in the question to add elements to the table , will give a column of the table for example , when adding the element " to " , the table is only with the "a", after adding "b", the table is "b,a" while the array will be [a,b] as it has to be , knows what I can change in my code to add elements to the table in order to give correct ?

  • I didn’t quite understand how the table is, you can post the question as is the table structure?

  • I’ve already put a picture

Browser other questions tagged

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