How to create HTML table inside javascript

Asked

Viewed 2,227 times

0

 for (var i = 0; i < t.length; i++) {
    options = options.concat('<option value="' + t[i].CodLinha + '">'+'--Saida Rodov Velha:'+ t[i].saida_Rodov_velha +'--Saida Rodov Nova:'+ t[i].saida_Rodov_Nova +'--Saida Interor:'+ t[i].saida_Interior +'--Numero Veiculo:'+ t[i].num_Veiculo + '</option>')                               
      }
        $('#NomeLinha').html(options).show();
        $('.carregando').hide();
   });
 } else {
        $('#NomeLinha').html('<option value=""> </option>');

} });

I have this code in javascript generating HTML and would like to know how to create a table that receives the data and display. There are three codes similar to the one that receive Nomeempresa, Nomecidade, Nomelinha and the last one would receive the schedules, I’m still learning HTML, Javascript and PHP, so I wanted to know how to replace this (options) and create the table in its place. And also if it has as the table to be dynamic, increased the size according to the received data.

  • So, this is a piece of javascript code that takes the data of a select and puts it inside a <option>, the other codes use a select in HTML for the user to choose an option, only the latter will only display the result. Where the question is, I wanted to put a table where the <option> I don’t know how.

  • That’s right, the user chooses a company, this company has several registered cities, the user chooses a city that has several registered bus lines, the user selects a line, that’s where the table enters to show the times for the selected line.

1 answer

2


How did I realize that your data select came from an object, I made a way to create a dynamic table from a array of objects. I imagine it is similar to what you have in the example of the question. I do not know if it was exactly what you wanted, but it serves to illustrate well.

My example object and Jquery function follows below:

var dados = [{
  "Nome": "Maria",
  "Idade": "18",
  "fone": "8888-9999"
}, {
  "Nome": "João",
  "Idade": "45",
  "fone": "9999-9999"
}, {
  "Nome": "Márcia",
  "Idade": "35",
  "fone": "4444-9999"
}];

function createTable(obj){
  // Criar a table
  $('body').append('<table></table>'); // Adiciona a tabela ao body
  var table = $('body').children('table'); // Seleciona a tabela

  // Criar o head da table
  var thead = "<tr>";
  for (title in obj[0]) {
    thead += "<th>" + title + "</th>";
  }
  thead += "</tr>";

  //Criar o body da table
  var tbody = "<tr>";
  obj.forEach(function(el, i) {
    for (item in el) {
      tbody += "<td>" + el[item] + "</td>";
    }
    tbody += "</tr>";
  })
	table.append(thead).append(tbody); // Adiciona a tabela completa ao body
}

createTable(dados); //Aplica a função ao objeto desejado.
table {
  background: #CCC;
  border: 1px solid #fff;
}

table td {
  padding: 15px;
  border: 1px solid #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In the above example, the data will be changed with a function, which will create the table, to add data, would be a different process, since we are talking about Jquery.

Another very simple way to do this is through the framework Angularjs. In case you’ve heard of it, you should know the capacity of this one, if not, keep this in mind.

With Angularjs, thanks to Data Biding, you only care about data manipulation, the Model, and the Controller will take responsibility for doing the Model and View interaction. This system is the MVC.

There is an example below the table creation from an object. Where you can add new items to the HTML table, just by adding them to the object, without any direct contact with HTML. As the data is changing, automatically the view will also change. Don’t worry about the framework attributes, consider the main idea of dynamicity.

Follow the code in Angular:

function tableCtrl($scope) {
  $scope.dados = [{
    "nome": "Maria",
    "idade": "18",
    "fone": "8888-9999"
  }, {
    "nome": "João",
    "idade": "45",
    "fone": "9999-9999"
  }, {
    "nome": "Márcia",
    "idade": "35",
    "fone": "4444-9999"
  }];
  
  $scope.adicionar = function(){
  	$scope.dados.push({
    	"nome": $scope.nome,
    	"idade": $scope.idade,
    	"fone": $scope.fone
    })
    $scope.nome = "";
    $scope.idade = "";
    $scope.fone = "";
    $scope.form.$setPristine();
  }
}
table {background: #CCC;border: 1px solid #fff;}

table td {padding: 15px;border: 1px solid #fff;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="tableCtrl">
  <table>
    <tr>
      <th>Nome</th>
      <th>Idade</th>
      <th>Fone</th>
    </tr>
    <tr ng-repeat="dado in dados">
      <td>{{dado.nome}}</td>
      <td>{{dado.idade}}</td>
      <td>{{dado.fone}}</td>
    </tr>
  </table>
<br>
<form name="form" ng-submit="adicionar()" >
  Nome: <input type="text"  ng-required="true"  ng-pattern="/[a-z]/g" ng-model="nome" ><br>
  Idade: <input type="text" ng-required="true"  ng-pattern="/[0-9]/g" ng-model="idade" ><br>
  Fone: <input type="text" ng-required="true" ng-pattern="/^\d{4,5}-\d{4}$/" ng-model="fone" ><br>
  <input ng-disabled="form.$invalid" type="submit" value="Adicionar">
</form>
</div>

Browser other questions tagged

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