Inserting Dates into HTML Table Cells - javascript

I am wanting to have a series of dates (mainly Month, Day, Year) displayed within a vertical arrangement of table cells on a web page. The first date needs to be the current date minus one day, with the next date in the sequence be the current date, The remaining dates need to incrementally be one day in future out to 16 days.
Can someone provide help me figure out how to do this? I have looked at and understand a Javascript to manipulate and display a single date (add or subtract) but am unable to get that date in a cell as well as figure out how to display the other multiple dates mentioned above in a HTML table.

Try this:
HTML
<table id="myTable"></table>
JavaScript
var table = document.getElementById('myTable')
var myDate = new Date();
myDate.setDate(myDate.getDate() - 1)
for(var i = 0; i < 16; i++)
{
var row = document.createElement('TR');
var cell = document.createElement('TD');
cell.innerText = myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getYear();
myDate.setDate(myDate.getDate() + 1)
row.appendChild(cell);
table.tBodies[0].appendChild(row);
}

Did you try myDate.toString() or myDate.toDateString()?
What you need to do is have some variables holding a date... Like this
var myDate = new Date();
Put whatever date in it that you fancy, then do this.
myDate.toDateString()
You can create your table in a loop in javascript and fill it with dates.
Did this help?

Option 1:
You can use write the output into the document like:
<table>
<tr>
<td><script type="text/javascript">document.write(mydate);</script></td>
...
</tr>
Option 2: generate the markup in javascript and then inject it into the DOM:
var markup = '<table>\
<tr>\
<td>' + mydate + '</td>\
</tr>\
...
</table>';
document.getElementById('contentDiv').innerHTML = markup;
Where you have a div element in your page:
<div id="contentDiv"></div>

Related

min Attribute for date input type not accepting variable value in javascript

I have the following html code to only accept date greater than or equal to the current date in vanilla javascript. However for some reason it does not seem to accept the minDate value in the <script> tag of the html file.
<body>
<form>
<td><label for="Ride_Start_Date">Ride Start Date</label></td>
<td><input type = "date" id="Ride_Start_Date" name="Ride_Start_Date"></td>
<td><button type="submit" class="submit">Submit Query</button></td>
</form>
<script>
var todayDate = new Date();
var month = todayDate.getMonth();
var year = todayDate.getUTCFullYear() - 0;
var tdate = todayDate.getDate();
if(month < 10){
month = "0" + month
}
if(tdate < 10){
tdate = "0" + tdate;
}
var minDate = year + "-" + month + "-" + tdate;
document.getElementById("Ride_Start_Date").setAttribute('min',minDate);
console.log(maxDate);
alert(" minDate="+minDate);
</script>
</body>
this does not work and doesn't limits the date input,
However when I use a hardcoded string while leaving everything else the same such as: document.getElementById("Ride_Start_Date").setAttribute('min',"2022-05-31");
this works perfectly.
I've tried looking at many answers but they all seem to work perfectly with a variable value for the setAttribute but mine does not.
What do I seem to be doing wrong here?
Would appreciate any and all assistance in this
You should use
var month = todayDate.getMonth() //getMonth from 0 to 11
Today is 2022-05-31.
You are trying to set 2022-04-31 as the minimum date.
This is the wrong date. That's why it doesn't work

Looping to grab HTML calendar date data attributes

I am manipulating a WordPress calendar plugin. I'm trying to add some CSS to the dates on the calendar for every day up to the current date. The plugin that I'm using, has the calendar in a table. The code for an individual day looks like this:
<td class="day-with-date" data-date="2017-5-10">
<div class="day-number">10</div>
</td>
I'm trying to use jQuery to loop through the dates from the data attribute.
This is my script.
$('.day-with-date .day-number').each(function(element){
var dataNumber = "[data-date=" + $(this).text() + "]";
var dataDateDay = "[data-date="+day+"]";
var textDay = $(this).text();
if(textDay <= day){
$('td.day-with-date .day-number').addClass('online-display');
}else if(textDay > day){
$('td.day-with-date .day-number').removeClass('online-display');
}else{
console.log("error douche");
}
});
What it's doing, is adding the CSS because textDay is <= than day. But it's removing the class after it's applied. I'm trying to get the CSS to add for all days up to today's date, then remove the CSS for days after.
How can I loop through the calendar dates, then apply my CSS class to all days up to the current date?
Thanks in advance!
There needs to be a change in your .each function:
$('.day-with-date .day-number').each(function(index) {
var dataNumber = "[data-date=" + $(this).text() + "]";
var dataDateDay = "[data-date=" + day + "]";
var textDay = $(this).text();
if (textDay <= day) {
$(this).addClass('online-display');
} else if (textDay > day) {
$(this).removeClass('online-display');
} else {
console.log("error douche");
}
});
You can try it here: https://jsfiddle.net/k99o5b39/
Try this
... // day has been defined
$('.day-with-date .day-number').each(function(element){
var parsedDay = Number.parseInt(element.text());
if(parsedDay <= day){
element.addClass('online-display');
} else {
element.removeClass('online-display');
}
});

How can I update the attributes of an HTML element inside a table cell?

I have a table which looks essentially like this
<!DOCTYPE html>
<html lang="en">
<body>
<table class="ui table" id="items">
<tbody>
<tr data-toggle="fieldset-entry">
<td><input id="items-0-quantity" name="items-0-quantity" type="text" value=""></td>
<td><input id="items-0-description" name="items-0-description" type="text" value=""></td>
</tr>
</body>
</html>
Using javascript, I'd like to have a button which adds a new row to the table, and I'd like the inputs in that new row to have id="items-1-xxx", and name="items-1-xxx, i.e. where there's a 0 in the original row I'd like a 1 in the new row.
I can make a new table row by cloning the old one, but I have not figured out how to modify the name and id attributes of the input.
Here's a sketch of what I've tried:
function cloneRow() {
var table = document.getElementById("items");
var original_row = table.rows[table.rows.length - 1];
var new_row = original_row.cloneNode(true);
// We have a new row and now we need to modify it as
// described in the question. The only way I've found
// is to grab the inner HTML:
var cell_contents = original_row.cells[0].innerHTML;
// Now we could do a bunch of string parsing and manipulations
// to increment the 0 to a 1 and stuff the modified HTML into
// new_row, but it seems there must be a better way.
// Finally insert the new row into the table.
original_row.parentNode.insertBefore(new_row, original_row.nextSibling);
}
What is the right way to update the input elements' id and name?
You could just build a new <td> and assign document.querySelectorAll('#items tr').length as the x in items-x-...:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length
, newitemQuantityText = 'items-' + itemcount + '-quantity'
, newitemDescriptionText = 'items-' + itemcount + '-description'
, newitem = document.createElement('tr')
, newitemQuantity = document.createElement('td')
, newitemDescription = document.createElement('td')
, newitemQuantityInput = document.createElement('input')
, newitemDescriptionInput = document.createElement('input');
newitemQuantityInput.id = newitemQuantityText;
newitemQuantityInput.name = newitemQuantityText;
newitemQuantity.appendChild(newitemQuantityInput);
newitemDescriptionInput.id = newitemDescriptionText;
newitemDescriptionInput.name = newitemDescriptionText;
newitemDescription.appendChild(newitemDescriptionInput);
newitem.appendChild(newitemQuantity);
newitem.appendChild(newitemDescription);
document.querySelector('#items').appendChild(newitem);
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items"></table>
However using good old innerHTML reads way better:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length;
items.innerHTML += '<tr><td>' +
'<input id="item-' + itemcount + '-quantity" name="item-' + itemcount + '-quantity">' +
'</td><td>' +
'<input id="item-' + itemcount + '-description" name="item-' + itemcount + '-description">' +
'</td></tr>';
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items">
</table>
You can separately reconstruct the node itself by using
createAttribute()
createElement()
Fiddle: http://jsfiddle.net/ztb9gq3d/1/
This is not the data oriented approach the question asks for, but a reasonably simple solution is
numRows = table.rows.length;
// Use a regexp so we can replace all instances of the number
// corresponding to what is currently the last table row.
var re = new RegExp((numRows - 1).toString(), "g")
for (var i = 0; i <= originalRow.cells.length - 1; i++) {
var originalHTML = originalRow.cells[i].innerHTML;
var newHTML = originalHTML.replace(re, numRows.toString());
newRow.cells[i].innerHTML = newHTML;
}
Obviously this only works if the number we replace doesn't exist elsewhere in the HTML string, so this is not a particularly good solution.
However, we could use a more complex regexp.
This solution does have the advantage that we don't need to hard-code anything except the parts we want to replace into the regexp.
Therefore, if the HTML in the table were to acquire additional parts in future development this solution will still work, up to the quality of the regexp as already mentioned.

Using jQuery to build HTML table

This is almost working but I am missing something. I am building an html table and I have JQuery. The idea is fairly simple. I have a list of names which will populate the first column of the table body. Next come two blank columns for some book keeping then a number of columns based on the number of days in the month of the date value passed into the function then a final bookkeeping column.
The general table structure is fine, the header and colgroups are fine. The thing that is biting me is the section of <td></td>'s in each body row that correspond the the days of the month. They are not showing up in the resulting table.
There are two loops. The first one builds the elements necessary to display the month day columns for the colgroup, header and body rows. Again, the colgroup and header bits are working. The $trb portion builds a single "row" of blank td elements that I hope to insert into each body row. The problem is $trb is not being appended/inserted to the body rows.
I'm not seeing this, ideas?
$(function() {
var list = ['11111 111', '2222 22222222', '3333333, 3333 3333333'];
buildMonthTable(new Date(), list);
function buildMonthTable(targetDate, list) {
var myDate = new Date(targetDate.getTime());
myDate.setDate(1);
myDate.setHours(0);
myDate.setMinutes(0);
myDate.setSeconds(0);
var lastDay = new Date(myDate.getTime());
var dayNames = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
var $table = $('<table>');
var $colGroup = $('<colgroup>');
var $thead = $('<thead>');
var $tbody = $('<tbody>');
var $trh = $('<tr>');
var $trb = $('<tr>');
$trh.append('<th>Name</th>');
$colGroup.append('<col class="colPlain colName"/>');
$trh.append('<th>Last Date</th>');
$colGroup.append('<col class="colPlain colRank"/>');
$trh.append('<th>Month Total</th>');
$colGroup.append('<col class="colPlain colTestDays"/>');
for (lastDay = new Date(myDate.getTime());
lastDay.getMonth() == myDate.getMonth();
lastDay.setTime(lastDay.getTime() + 86400000)) {
$trh.append('<th>' + lastDay.getDate() + '<br/>'
+ dayNames[lastDay.getDay()] + '</th>');
if (lastDay.getDay() % 2 == 0) {
$colGroup.append('<col class="colPlain colDay"/>');
} else {
$colGroup.append('<col class="colShade colDay"/>');
}
$trb.append('<td> </td>');
}
$trh.append('<th>Practice Days This Month</th>');
$colGroup.append('<col class="colPlain colTestDays"/>');
$table.append($colGroup);
$thead.append($trh);
$table.append($thead);
for (var i = 0; i <list.length; i++) {
var $bodyRow = $('<tr></tr>');
$bodyRow.append('<td>' + list[i]
+ '</td><td> </td><td> </td>');
console.log($trb);
$bodyRow.append($trb); // <===== this is not appending
$bodyRow.append('<td> </td>');
$tbody.append($bodyRow);
}
$table.append($tbody);
$("#content").append($table);
}
});
rafaelcastrocouto is correct, it is outputting... so I think you're problem is here:
var $bodyRow = $('<tr></tr>');
You want to have the tr tag at the top and close the tr at the bottom instead.
Also, I don't see your closing table tag either.
The trb is appending as you can see here
$trb.append($('<p>x</p>')); // this will make you see lots of "x" in your table
$bodyRow.append($trb); // <===== so this is appending
You should not append a tr(trb) inside another tr(bodyRow) the way you are doing and I guess you do not really want to do that rigth?!

Update 2nd Textbox Based On Popup Calendar Selection

I am using the JavaScript-based popup calendar from dynamic drive named
"Xin's Popup Calendar" and it works perfectly. But, I want to be able to
adjust the date of a 2nd textbox based on the selection.
For example, I want to be able to automatically adjust it to +1 month of
whatever date was selected in the popup. How can I do that?
Here is an example:
<input type="text" name="firstinput" size=20>
<small>Select Date</small>
<p>
<input type="text" name="secondinput" size=20>
<small>Select Date</small>
</p>
If the firstinput date is 3/21/10, I want the secondinput to change to 4/21/10 at the same time.
There are two parts to this: (1) a function to add a month to a data and (2) the change event handler to the textbox. This solution is very specific to the Xin Pop Up Calendar.
function addMonth(d,month){
t = new Date (d);
t.setMonth(d.getMonth()+ month) ;
if (t.getDate() < d.getDate())
{
t.setDate(0);
}
return t;
}
$("input[name='firstinput']").change(function(){
var dt = $(this).val();
var yr = dt.substring(0,4);
var mo = dt.substring(5,7);
var dy = dt.substring(8,10);
var firstDate=new Date();
firstDate.setFullYear(yr,mo-1,dy);
var secondDate = addMonth(firstDate,1);
$("input[name='firstinput']").val(secondDate.getFullYear() + "/" + secondDate.getDate() + "/" + secondDate.getMonth()+1);
});

Categories

Resources