nad
nad

Reputation: 2850

HTML table not showing table header

I have an html table with 3 columns and any number of rows (based on a database output.)

    var fields = ['a','b','c'];  //variable from database
    var data = ['p', 'q', 'r'];  //variable from database
    var who = ['x', 'y', 'z'];  //variable from database
    
    $(function() {
        var table = $("#resultTable");
        var rowNum = 3;
        var resultHtml = '';
    
    	for(var i = 0 ; i < rowNum ; i++) {
    		resultHtml += ["<tr>",
    	 "<td>",
    	  fields[i],
    	 "</td>",
    	 "<td>",
    	  data[i],
    	 "</td>",
    	 "<td>",
    	  who[i],
    	 "</td>",
    	 '</tr>'].join("\n");
    	}
    
    	table.html(resultHtml);
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
            <tr>
              <th>Question</th>
              <th>Decision</th>
              <th>Whose Decision</th>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </table>

The table shows the content properly but doesn't show the headers of each of the column such as Question, Decision, Whose Decision

What am I missing?

Upvotes: 0

Views: 1382

Answers (4)

Krushnakant Ladani
Krushnakant Ladani

Reputation: 673

You replaced whole html. You need to apped html like

table.append(resultHtml);

Upvotes: 1

Dekel
Dekel

Reputation: 62536

By using table.html(...) you override the entire content of your table (include the header).

You can use something like that:

var fields = ['a','b','c'];  //variable from database
var data = ['p', 'q', 'r'];  //variable from database
var who = ['x', 'y', 'z'];  //variable from database

$(function() {
    var table = $("#resultTable");
    var rowNum = 3;
    var resultHtml = $('<table>').append(table.find('tr').first()).html();

    for(var i = 0 ; i < rowNum ; i++) {
        resultHtml += ["<tr>",
     "<td>",
      fields[i],
     "</td>",
     "<td>",
      data[i],
     "</td>",
     "<td>",
      who[i],
     "</td>",
     '</tr>'].join("\n");
    }

    table.html(resultHtml);
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
  <tr>
    <th>Question</th>
    <th>Decision</th>
    <th>Whose Decision</th>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

Upvotes: 1

see sharper
see sharper

Reputation: 12025

You are overwriting the table in the javascript from what I can see. table.html(resultHtml) is replacing what you have in the html code.

Upvotes: 0

The KNVB
The KNVB

Reputation: 3844

Because you use resultHtml to replace table HTML code.

Upvotes: 0

Related Questions