Dynamically add <td>'s to a table - javascript

I am trying to create a table of 30 days of dates, starting from today.
right now I have this working, but it is being returned as a string.
I want to add a <td> with each date returned to my table.
My code is this
HTML
<table>
<tbody>
<tr>
<td></td> <!-- Add Each Date here -->
</tr>
</tbody>
</table>
JS
var date = moment(),
begin = moment(date).startOf('week').isoWeekday(1);
var str = "";
for (var i=0; i<30; i++) {
str += begin.format("MMM Do") + '<br>';
begin.add('days', 1);
}
// Would like to add date to each <td> and add <td> to the table
document.body.innerHTML = str;
DEMO

Just need slight addition to your existing code see below,
var date = moment(),
begin = moment(date).startOf('week').isoWeekday(1);
var str = [];
for (var i=0; i<30; i++) {
str.push('<td>' + begin.format("MMM Do") + '</td>');
begin.add('days', 1);
}
$('#myTable tbody').append('<tr>' + str.join('') + '</tr>');
DEMO: http://jsfiddle.net/wzdr2/

This should work:
for (var i=0; i<30; i++) {
$("table tr").append("<td>" + begin.format("MMM Do") + "</td>");
begin.add('days', 1);
}

Try not to append to DOM each time, it'l make it slower and inefficient especially if you have too many items to be appended. Instead add them up and append in the end.
var str = "", $tds= [];
for (var i=0; i<30; i++) {
$tds.push('<td>' + begin.format("MMM Do") + '</td>'); //push the tds to the temp array
begin.add('days', 1);
}
// Would like to add date to each <td> and add <td> to the table
$('table tr').append($tds); //append in the end
Demo

You could append them as you go. Like so...
http://jsfiddle.net/jzKMS/
for (var i=0; i<30; i++) {
$('#dates tbody').append('<tr><td>' + begin.format("MMM Do") + '</td></tr>');
begin.add('days', 1);
}
Or, for faster running, build your elements first and append once at the end.

Related

Create new <tr>as text after 3rd <td> in JS

i want to create new table row as text <tr> after every third table data<td> from user input.
It have to be like this:
<table border="3" align="center" style="width: 100%;">
<tr>
<td><a href="link"><img src="link"></td>
<td><a href="lin"><img src="link"></td>
<td><a href="link"><img src="link"></td>
</tr>
<tr>
<td><a href="link"><img src="link"></td>
<td><a href="lin"><img src="link"></td>
<td><a href="link"><img src="link"></td>
</tr>
</table>
My code:
<script type="text/javascript">
let x = 0;
const data = Array();
document.getElementById('btn').addEventListener("click", fun);
function fun() {
var val = document.getElementById('imagename').value;
source = val;
img = document.createElement('img');
img.src = source;
document.body.appendChild(img);
// move child to up
var before = document.getElementById('before');
before.insertBefore(img, before.children[0]);
/*var html = document.getElementById('before').innerHTML;
document.getElementById('code').innerHTML = '<img src=' + src + '>';*/
document.getElementById('code').innerText = '<img src="' + source + '">';
data[x] = document.getElementById('imagename').value;
x++;
}
document.getElementById('pasteBtn').addEventListener("click", makeCode);
function makeCode(){
let resultData = "<tr>";
for (let i = 0; i < data.length; i++){
resultData += "<td>" + '<a href="' + data[i] + '">' + '<img src="' + data[i] + '"></td>\n';
if(i % 3 == 0){
resultdata += '</tr><tr>';
}
}
cssText = 'tr {width: 100%; display: flex;} td {width: 100%;}';
tableText = '\n<table border="3" align="center" style="width: 100%;">\n';
document.getElementById("paste").innerText = "<style>" + cssText + "</style>" + tableText + resultData;
}
</script>
I was trying with modulo but nothing happened. It have to be done in JS, not JQuery.
Your code has a couple of problems, which have been mentioned in the comments. The last created row is not closed. Some browsers nowadays automatically solve this problem by adding the closing tag for that row, but it leaves you with a floating row.
A second problem is your modulo calculation. Since javascript arrays start at 0 and not at 1 you modulo creates the row to early, for:
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
A row is created containing ONLY the first value. This can be fixed by changing the modulo calculation to i + 1 % 3, however it might not immediatly be clear why you seemingly randomly add the 1.
Another option is to introduce a counter. It is clear what the counter does, it counts. It is also clear to where it counts, 3. By moving the closing and starting of the row to before the adding of the cell you prevent floating rows. You only start a new row, when you actually need one. Important still is to close the row, but as said before, there are browsers that do this, but you should not rely on that.
let resultData = "<tr>";
let counter = 0;
for (let i in data){
if(counter == 3){
resultdata += '</tr><tr>';
counter = 0;
}
resultData += "<td>" + '<a href="' + data[i] + '">' + '<img src="' + data[i] + '"></td>\n';
counter++;
}
resultdata += "</tr>";
Personally I prefer to use a for...in loop for looping over an array, but that is personal preference
There are many ways to accomplish what you are looking for.
For my answer I chunked the array into groups of 3, then I loop through each element in each group.
I also chose to use createElement instead of using the string versions.
let table = document.querySelector("#paste");
let data = [
1,2,3,4,5,6,7,8,9
];
while((row = data.splice(0, 3)).length){
let tr = document.createElement("tr");
for(z=0;z<=row.length-1;z++){
let td = document.createElement("td");
let link = document.createElement("a");
let img = document.createElement("img");
img.src = row[z];
link.href = row[z];
link.appendChild(img)
td.appendChild(link)
tr.appendChild(td)
}
table.appendChild(tr)
}
<table id="paste"></table>
Adding EventListener to MakeCode.Btn.getting the count of td each row has with data.length/3(9/3=3);so each row will have 3 td's.
Creating index variable to iterate over the array.
creating Two ForLoops.
1st loop will create a row with an id of r(i).first row will have an id of id="r1".
2nd loop will get the row that was created in the first loop and it will add td tCount times which is 3 in this case.
& data will also be added inside each td with ${data[index]}
incrementing the index every time a td is added.
when index is equal to data.length getting the innerHtml of the table and pasting it in the text area as a value.and setting the innerHtml of the actual table to "" empty
const data = [
"hello",
"world",
"code",
"coding",
"javascript",
"css",
"html",
"react",
"scss"
];
let table = document.getElementById("table");
let btn = document.getElementById("pasteBtn");
let textBox = document.getElementById("textbox");
btn.addEventListener("click", () => {
let tdCount = data.length / 3;
let index = 0;
for (let i = 1; i <= 3; i++) {
table.innerHTML += `<tr id="r${i}"></tr>`;
for (let j = 1; j <= tdCount; j++) {
document.getElementById(`r${i}`).innerHTML += `<td><a href="link"><img src="link"></td>`;
index++;
if (index === data.length) {
let finalHtml = document.getElementById("table").innerHTML;
textBox.value = finalHtml;
document.getElementById("table").innerHTML = "";
}
}
}
});
textarea {
width: 100%;
height: 200px;
}
<button id="pasteBtn">makeCode</button>
<table border="3" align="center" style="width: 100%;">
<tbody id="table">
</tbody>
</table>
<textarea id="textbox"></textarea>
As mentioned #imvain2's answer, it is better to use js document.createElement over the string to create the elements. And here is an approach that uses a single loop.
HTML:
<table id="data-table"></table>
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const table = document.getElementById('data-table');
const addRows = (data) => {
let tableRow = null;
data.forEach((item, index) => {
// adds a new row on first and then after every third "td"
if (index % 3 === 0) {
tableRow = document.createElement('tr');
tableRow.id = 'tr' + (index + 1);
table.appendChild(tableRow);
}
const tableData = document.createElement('td');
tableRow.appendChild(tableData);
const link = document.createElement('a');
link.href = item;
link.title = item;
tableData.appendChild(link);
const img = document.createElement('img');
img.src = item;
link.appendChild(img);
});
};
addRows(data);

Array.sort not working correctly

I need the sort function to sort the dates from the earliest date to the latest date. What can I do to fix this in my tasks table?
var tasks = new Array();
var index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
//add array and populate from tempdate and temptask
//generate html table from 2d javascript array
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a,b){return new Date(b.Date).getTime() - new Date(a.Date).getTime()});
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
I have tried many different syntax variations and can not get the sort function to sort in descending order
Since the date is represented as
the number of milliseconds since 1 January, 1970 UTC (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
the sorting order you are looking for is ascending not descending.
Also, as #birdspider already commented, there is no use of creating new Date objects and invoking the getTime() method. They are comparable as they are.
To summarize the above points, try using the following sorting function:
function sortDatesAsc(tempdateA, tempdateB) {
return tempdateA - tempdateB < 0 ? -1 : (tempdateA > tempdateB ? 1 : 0);
}
tasks.sort(sortDatesAsc);
You're subtracting a.Date from b.Date, exactly the reverse of what you want.
Flip those around (and remove the unnecessary new Date() wrappers, although they're not actually breaking anything) and you'll get the correct sort:
var tasks = [],
index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a, b) {
return a.Date.getTime() - b.Date.getTime()
});
var tablecode = "<table class='tasktable'>" +
"<tr>" +
"<th>Date</th>" +
"<th>Task</th>" +
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode += "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode += "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
document.getElementById('add').addEventListener('click', addTask);
<p>Task:
<input type="text" id="taskinfo" /></p>
<p>Date:
<input type="date" id="taskdate" /></p>
<button id="add">add</button>
<div id="bottomright"></div>

i want to create new table dynamically and removed it by same button using jquery?

I want to show updated rows no every time. I have this code .want to remove and generate again as this same
var table = $('#table').children();
for (var j = i; j < result.length; j++) {
table.append("<tr><td>" + (j + 1) + "</td><td><b>" + result[j].VoterName + "</b></td><td><b>" + result[j].VoterContact + "</b></td><td><button>X</button></td></tr>");
i++;
}
function createOrDeleteTable(){
console.log("wadawdawd");
if($("#btn").attr("created") === "false") {
$("#btn").attr("created","true");
var tabledata = "<table>"
+ "<tr>"
+"<th> hey </th>"
+"<th> hello </th>"
+ "</tr>"
+ "</table>";
console.log(tabledata);
$("#appendHere").html(tabledata);
} else {
$("#btn").attr("created","false");
$("#appendHere").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createOrDeleteTable();" created="false" id="btn"> create table </button>
<div id="appendHere"> </div>

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

Making a rows value to be anothers text with jquery

I have a table with 2 rows, the first has an input for quantity and the following has to output that same value. Since I'm using jQuery this is my code:
var i, quant;
for (i = 0; i < $(".qnt").length; i++){
$(".qnt:eq(" + i + ")").keyup(function(){
quant = $(this).val();
console.log($(this));
console.log(i);
console.log($(".cst:eq(" + i + ")"));
$(".cst:eq(" + i + ")").text(quant);
});
}
And the sample for the rows is :
<tr>
<td><input class="qnt"/></td><td class="cst"></td>
</tr>
The jsfiddle is : http://jsfiddle.net/qrhJ4/
Question : why is the .cst selector not working and how do I make it work?
You are over-complicating things, try something like:
$('.qnt').keyup(function() {
$(this).parent().next('.cst').text(this.value);
});
http://jsfiddle.net/aasqW/

Categories

Resources