Reputation:
I am trying to append a table to div
:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function addStuff() {
var html = '<table>';
$.each(function() {
html += '<tr><td>' + '</td></tr>';
});
html += '</table>';
$("#divResults").append(html);
}
</script>
</head>
<body>
<div id="divResults"></div>
<button onclick="addStuff()">Add Stuff</button>
</body>
</html>
But it is not working. I want to dynamically add table to the DIV block.
Upvotes: 6
Views: 52758
Reputation: 36438
each
what? Your $.each
method needs to loop over something. e.g.
function addStuff() {
var words = ['one', 'two', 'three'];
var html = '<table>';
$.each(words, function(i, word) {
html += '<tr><td>' + word + '</td></tr>';
});
html += '</table>';
$("#divResults").append(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divResults"></div>
<button onclick="addStuff()">Add Stuff</button>
Upvotes: 6
Reputation: 1
You should use the following:
var myTable = document.createElement("img");
var row1 = gameGrid.insertRow(0);
var row2 = gameGrid.insertRow(1);
var col1 = row1.insertCell(0);
var col2 = row2.insertCell(1);
col1.innerText = "some thing";
document.getElementById("divResults").innerHtml = myTable;
Upvotes: 0
Reputation: 5507
You want to append table to the DIV try this....
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function addTable()
{
$('#divResults').append('<table width="320" border="1"><tr><td colspan="2" rowspan="1">' + " wdw" + '</td></tr><tr><td width="118">' + "sxs" + '</td><td width="186">' + "xs" + '</td></tr></table>');
}
</script>
</head>
<body>
<div id="divResults">
</div>
<button onclick="addTable()">Add Stuff</button>
</body>
</html>
Upvotes: 12
Reputation:
You're using $.each()
but not passing any collection for it to iterate.
// ---v---no collection?
$.each(function() {
html += '<tr><td>' + '</td></tr>';
});
Normally you'd pass an Array or something.
$.each(["foo", "bar", "baz"], function(i, val) {
html += '<tr><td>' + val + '</td></tr>';
});
DEMO: http://jsfiddle.net/VLfvv/
Note that this is a little different from the .each()
method, which operates on a jQuery object, so the members of the object become the value.
$(".foobar").each(function(i, el) {
// do something with the element
});
Also note that if all you want is to add this empty table, it could easily be done without jQuery.
function addStuff() {
var html = '<table>';
for (var i = 0; i < 10; i++)
html += '<tr><td>' + '</td></tr>';
html += '</table>';
document.getElementById("divResults")
.insertAdjacentHTML("beforeend", html);
}
Upvotes: 3