Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table with twitter bootstrap and jQuery

I have this js part of script:

jQuery.each(data, function(index, value) {
     $("table_div").append("<td>" + value + "</td>");
 });

I want use this for create a table with twitter bootstrap. In the html page there is this table element:

<table class="table table-striped" id="table_div">
</table>

But this solution doesn't works. How I have to do? Thank you!

like image 334
sharkbait Avatar asked Dec 09 '22 20:12

sharkbait


2 Answers

First of all, you're not appending any <tr> elements which are needed in a table, and secondly you're referring to $("table_div") instead of $("#table_div") (the hashtag # means that you're referring to an ID, just like in CSS).

jQuery.each(data, function(index, value) {
     $("#table_div").append("<tr><td>" + value + "</td></tr>");
});
like image 66
h2ooooooo Avatar answered Dec 25 '22 21:12

h2ooooooo


Besides referring to the node <table_div> instead of the id #table_div you don't want to append anything to the table node.

You should take a look at this as well as here and here.

You should use tbody when using Twitters Bootstrap anyways for example, like so:

<table id="table_div" class="table table-striped">
  <tbody></tbody>
<table>

here the right js

for (i in data) {
  $('#table_div > tbody:last').append('<tr><td>'+data[i]+'</td></tr>');
}

For more research look here Add table row in jQuery

Edit:

Ok i wrote you an entire example using twitters bootstrap and jQuery. This works, if it doesn't for your data array, something is wrong with it.

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
</head>
<body>
<table class="table table-striped" id="my-table">
<tbody>
</tbody>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.js"></script>
<script type="text/javascript">
var data = ["foo","bar"];
$(document).ready(function(){
        $.each(data, function(i,item){
                $('#my-table > tbody:last').append('<tr><td>'+item+'</td></tr>');
        });
});
</script>
</body>
</html>
like image 42
codingjoe Avatar answered Dec 25 '22 19:12

codingjoe