Jaanus
Jaanus

Reputation: 16541

Adding rows and columns to HTML with jQuery/JavaScript

this is my html code:

<h3>Ilm selles linnas</h3>
<table>
    <tr>
        <th>id</th>
        <th>city_id</th>
        <th>temp</th>
        <th>date</th>
    </tr>
    <div id="info"></div>
</table>

this is my script:

function(data) {
            $('#info').empty();
            var html = "";
            for(var i = 0; i < data.length; i++) {
                html += "<tr>"+
                    "<td>"+data[i].id+"</td>"+
                    "<td>"+data[i].city_id+"</td>"+
                    "<td>"+data[i].temperature+"</td>"+
                    "<td>"+data[i].date+"</td>"+
                "</tr>";                
            }
            $('#info').append(html);
}

After this is done, in the real ouput this happens:

enter image description here

So:

1) All the info is higher than table headers (<th> tag)

2) All the info isn't in the column, but just smashed together

3) None of the info is showed in HTML source.

What must I change to make it look as it should?

Feel free to ask any questions.

Upvotes: 0

Views: 309

Answers (4)

Samich
Samich

Reputation: 30115

Just remove your <div id="info"></div> and append directly to the table.

$('table tr:gt(0)').remove();

var html = "";
$(data).each(function() {
    html += "<tr>"+
                "<td>"+this.id+"</td>"+
                "<td>"+this.city_id+"</td>"+
                "<td>"+this.temperature+"</td>"+
                "<td>"+this.date+"</td>"+
            "</tr>";    
});   

$('table').append(html);

Code: http://jsfiddle.net/Xdbqs/5/

Upvotes: 5

pfunc
pfunc

Reputation: 1305

Don't use a div. You could just use a and your code would work.

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

<table id="info">
    <tr>
        <th>id</th>
        <th>city_id</th>
        <th>temp</th>
        <th>date</th>
    </tr>
</table>

As stated it's your markup. Change it to the above.

Upvotes: 0

graphicdivine
graphicdivine

Reputation: 11211

You can't put a div in a table. Try this:

<table id="datatable">
<tr>
    <th>id</th>
    <th>city_id</th>
    <th>temp</th>
    <th>date</th>
</tr>
</table>

function(data) {
        var html = "";
        for(var i = 0; i < data.length; i++) {
            html += "<tr>"+
                "<td>"+data[i].id+"</td>"+
                "<td>"+data[i].city_id+"</td>"+
                "<td>"+data[i].temperature+"</td>"+
                "<td>"+data[i].date+"</td>"+
            "</tr>";                
        }
        $('#datatable').append(html);
}

Upvotes: 1

Related Questions