I'm trying to generate dynamic table with jquery. So stuck on appending in appending.
Need to write something like this. But of course it have wrong syntax :)
var $tbl = $('<table>').attr('id', 'basicTable');
$tbl.append($('<tr>').for(var i = 0; i < 10; i++){($('<td>')});
$('body').append($tbl);
Try the following:
var $tr = $('<tr></tr>');
var i;
for (i = 0; i < 10; i++) {
$tr.append('<td></td>');
}
var $tbl = $('<table></table>').attr('id', 'basicTable');
$tbl.append($tr);
$('body').append($tbl);
See here for jsFiddle.
This should do it -
var cont = [];
for (var i = 0;i<10;i++) cont.push('<td></td>');
var $tbl = $('<table>').attr('id', 'basicTable');
$tbl.append('<tr>' + cont.join('') + '</tr>');
Demo - http://jsfiddle.net/yeYWP/
See this question for further methods on adding multiple elements of the same type via jQuery - How should I add multiple identical elements to a div with jQuery
Here's how to do it with fewer variables:
var row = $('<tr />');
for(var i = 0; i < 10; i++)
row.append('<td />');
$('body').append(
$('<table />').attr('id', 'basicTable').append(row);
);
Related
This is a really simple question but I don't know why it doesn't work.
I have an array with 3 items inside. And I have a container which I would like to insert a number of divs based on the number of items in my array. I used a for loop for this but it is only creating one div. Should it not create 3?
for (var i = 0; i < array.length; i++) {
var container = document.getElementById("container");
container.innerHTML = '<div class="box"></div>';
}
here is a fiddle to demonstrate further fiddle
Move container out of the loop, it is not required inside it.
Append the innerHTML in each iteration.
var container = document.getElementById("container");
for (var i = 0; i < array.length; i++) {
container.innerHTML += '<div class="box"></div>';
}
Edit:
Thanks Canon, for your comments. I also wanted to suggest the same approach as yours, but I got busy in some other work after posting the answer [No excuses :)] Updating the answer:
var htmlElements = "";
for (var i = 0; i < array.length; i++) {
htmlElements += '<div class="box"></div>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
This may look like involving more lines of code but this will be more efficient and less error-prone than the previous solution.
Replace = to +=
As per the #canon comment, edited answer are below
var innerHTMLString = "";
forloop {
innerHTMLString += '<div class="box"></div>';
}
document.getElementById("htmlElements").innerHTML = innerHTMLString
Replace this
container.innerHTML = '<div class="box"></div>';
with this
container.innerHTML += '<div class="box"></div>';
If you want to create more than one, you must call createElement more than once.
d=document.createElement("div");
line into the j loop.
If you call appendChild passing in an element that's already in the DOM, it's moved, not copied.
window.onload=function()
{
var i=0;
var j=0;
for (i=1; i<=8; i++)
{
for (j=1; j<=8; j++)
{
if ((i%2!=0 && j%2==0)||(i%2==0 && j%2!=0))
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="black";
}
else
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="white";
}
}
}
}
Javascript Method -
var container = document.getElementById("container");
for (var i = 0; i < array.length; i++) {
container.innerHTML += '<div class="box"></div>';
}
jQuery Method -
foreach(array as value){
$("#container").append('<div class="box"></div>')
}
For further references; what about this approach? :)
HTML:
<div class="particles">
<div class="parts"></div>
</div>
JavaScript:
// Cloning divs where particles go in order not to put 300 of them in the markup :)
const node = document.querySelector(".parts");
[...Array(300)].forEach(_ =>
node.parentNode.insertBefore(node.cloneNode(true), node)
);
I trying to get the <th> content of the clicked <td> item.
here is the fiddle: http://jsfiddle.net/zrccq447/
the thing is, the <th> can have colspan 2 or 3, this is the point where I am stuck. this is my code
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + (clicked_pos) + ')').text();
var xy = td.text();
alert(x);
});
i want x to be the <th> of clicked td. the problem is now that if you click on some td that shares the th with other tds, i am getting the wrong th.
appreciate any help
I've updated your JsFiddle with the answer found here: Finding a colSpan Header for one of the cells or td's is Spans
JsFiddle: http://jsfiddle.net/zrccq447/4/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + thLocator[clicked_pos] + ')').text();
var xy = td.text();
alert(x);
});
var thLocator = [], colCount = 1;
$('#table9').find('tr:first th').each(function () {
for (var i = 0; i < this.colSpan; i++) {
thLocator.push(colCount);
}
colCount++;
});
Following on from my comment you need to sum up the colspans (or default 1) for each TH until you get enough to match the column you desire:
http://jsfiddle.net/TrueBlueAussie/zrccq447/5/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var cols = 0;
var $table = td.closest('table');
var $ths = $table.find('tr th');
for (var i = 1; i < $ths.length; i++) {
var $th = $ths.eq(i);
cols += ~~$th.attr('colspan') || 1;
if (cols >= clicked_pos) {
var x = $th.text();
alert(x);
break;
}
}
});
I tried to keep it generic, so it finds the appropriate table and headers on the fly.
One approach is to get store a reference to each TH, in order, in an array and call the text from the array based on the location of the td.
var thholder = $('table th'),
th = [];
for(var i = 0; i < thholder.length; i++) {
var thi = $(thholder[i]);
for(var j = 0; j < (thi.attr('colspan') || 1); j++) {
th.push(thi);
}
}
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
alert(th[clicked_pos].text());
});
http://jsfiddle.net/zrccq447/3/
This code is not optimised, but shows the approach:
Loop through all the TH in the table.
If the TH does not have the attribute 'colspan', then set the attribute to a value of 1.
Create a loop for each value of colspan and save a reference to the current TH in the array.
When you click on a TD, get it's clicked position and retrieve the text of the TH at that position in the array and alert it :)
I can't separate row and column td's as I create a 2d table with jquery..
How do I create 10 rows 10 columns 2d table:
what I have done so far:
$(document).ready(function () {
for (var i = 1; i <= 10; i++) {
$('.box').append('<td/>' + '</p>');
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
}
});
http://jsfiddle.net/VS37n/
thnx in advance!
You want a table that has 10 columns and 10 rows.
var rows = 10;
var cols = 10;
In an HTML table structure, rows come first in the hierarchy, so, create those first:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
//Here we will append the columns to the row before appending it to the box.
box.append(tr);
}
});
The above code only makes 10 rows for us. Now we need to add 10 columns to each row:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
for (var c = 0; c < cols; c++) {
tr.append($('<td><p></p></td>')); //Create the table cell, with a p element as in your example, and append it to the row.
}
box.append(tr);
}
});
See this FIDDLE
UPDATE
I just noticed that the jQuery selector from your post selects the <div> element with class .box. You want to add these rows and columns, however, to a <table> element, which doesn't exist. I'd suggest you add a <table> element into your HTML, or, add it with Javascript before adding the rows.
If you can add a <table> element inside of your .box div, then you would just change the following line:
var box = $('.box');
to:
var box = $('.box table:first');
If you can't change the HTML for some reason, then you can dynamically create the table before the rows and columns:
var box = $('<table>').appendTo('.box');
Is this what you're trying to do?
$(document).ready(function () {
var tdHtml = "":
var trHtml = "";
var tableHtml = "";
for(var i=1;i<=10;i++)
{
tdHtml += "<td></td>";
}
for(var j=1;j<=10;j++);
{
trHtml += ("<tr>" + tdHtml + "</tr>");
}
tableHtml = ("<table>" + trHtml + "</table>");
$('.box').innerHtml(tableHtml);
});
You had a ; after your for loop :
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
Furthermore, you are not adding <tr> elements.
See the updated fiddle
I want to get all classes of the HTML element on my page, split it and store it in array. After that I want to write it into my table in the div with the id "table" which I already have.
So far I have this code:
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
// code
}
<div id="test><!-- table goes here --></div>
Can you help me with the rest?
btw, the HTML element has the classes from a modernizr.js.
PS: The code is combination of pure JS and jQuery. Because I dont know how to get all classes of the HTML element in pure JS. Any Idea?
If you're trying to remove jQuery altogether use this:
// Get array of classes without jQuery
var array = document.getElementsByTagName('html')[0].className.split(/\s+/);
var arrayLength = array.length;
var theTable = document.createElement('table');
// Note, don't forget the var keyword!
for (var i = 0, tr, td; i < arrayLength; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(array[i]));
tr.appendChild(td);
theTable.appendChild(tr);
}
document.getElementById('table').appendChild(theTable);
if you have a table already in the html
<div id="test><table >
</table>
</div>
you can simply append new rows to it,
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
$("#test table") .append('<tr><td>'+array[i]+'</td></tr>')
}
It is not clear if you want the class names per row or per column. These examples are one class name per row. Try this:
var elm = $('#test'),
table = $('<table>').appendTo(elm);
$(document.documentElement.className.split(' ').each(function() {
table.append('<tr><td>'+this+'</td></tr>');
});
I used native code to get the classNames of the HTML element: document.documentElement.className, but you might as well use $('html').attr('class').
A native JS example using innerHTML:
var d = window.document,
elm = d.getElementById('test'),
html = '<table>',
classes = d.documentElement.classNames.split(' '),
i = 0;
for(; classes[i]; i++) {
html += '<tr><td>' + classes[i] + '</td></tr>';
}
elm.innerHTML = html + '</table>;
Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.