create an automatic bold for table by the ID ?? with javascript - javascript

first of all I apologize for my bad English, I want to make a JavaScript for a tabele who makes himself automatically by the ID Bold, just like this one here but the code is not only for weeks for tabele
the table has therefore different time input I will when the time is for example 08:00 clock, the tabele from 08:15 to mark Irish always +1
<td id="1">08:00</td>
<td id="1">BEKA-KAQANIK</td>
</tr>
<tr>
<td id="2">08:15</td>
<td id="2">MEDINA</td>
Here is an example but it is only on weekdays
http://jsfiddle.net/c5bHx/
var days = 'sunday,monday,tuesday,wednesday,thursday,friday,saturday'.split(',');
document.getElementById( days[(new Date()).getDay()] ).className = 'bold';
.bold {
font-weight:bold;
}
<div id="monday">Monday: 12:00-2:00</div>
<div id="tuesday">Tuesday: 11:00-3:00</div>
<div id="wednesday">wednesday: 12:00-2:00</div>
<div id="thursday">thursday: 11:00-3:00</div>
<div id="friday">friday: 12:00-2:00</div>
<div id="saturday">saturday: 11:00-3:00</div>
<div id="sunday">sunday: 12:00-2:00</div>

I'm not sure if I understand your question correctly, but here is an example JSFIDDLE. It might help with what you're trying to accomplish.
<table>
<tr id="1530">
<td>15:30</td>
<td>A</td>
</tr>
<tr id="1545">
<td>15:45</td>
<td>B</td>
</tr>
<tr id="1600">
<td>16:00</td>
<td>C</td>
</tr>
</table>
// Initialize new Date object.
var currentDate = new Date();
// Get the hour
var currentHour = currentDate.getHours();
// Get the minutes
var currentMinute = currentDate.getMinutes();
// Bin the minutes to 15 minute increments by using modulus
// For example, xx:33 becomes 30
var minuteBin = currentMinute - (currentMinute % 15);
// Create a string that matches the HTML ids
var idString = "" + currentHour + minuteBin;
// Set the matching div class to 'bold'
document.getElementById(idString).className = 'bold';
// Log variables to console for debugging
console.log("Time =",currentHour,":",currentMinute,"bin =",minuteBin,"idString =",idString);
This example is meant for GMT-0400 (EDT). This will give different results in different time zones.
If I've misunderstood anything, please let me know and I will do my best to update my answer. Hope that helps!

Related

Keep getting 'undefined, undefined' saved in local storage

I'm making a day planner app with hour blocks from 0900-1700 where the inputs can be saved into local storage and then are automatically retrieved on page refresh. Having issues with my code currently with it only saving 'undefined, undefined' in the console, and not returning anything on page refresh. Any help is appreciated. Thanks!
HTML:
<tr class="row" id="15">
<th scope="time" id="hour15" class="time">15:00</th>
<td><input type="text" class= "hourinput"/></td>
<td class="btnContainer">
<button class="saveBtn"><i class="fas fa-save"></i></button>
</td>
</tr>
<tr class="row" id="16">
<th scope="time" id="hour16" class="time">16:00</th>
<td><input type="text" class= "hourinput"/></td>
<td class="btnContainer">
<button class="saveBtn"><i class="fas fa-save"></i></button>
</td>
</tr>
JS:
// Moment.js to auto-update time on webpage------------------------------------------//
var update = function () {
date = moment(new Date());
currentDay.html(date.format('dddd, MMMM Do YYYY, HH:mm:ss a'));
};
$(document).ready(function(){
currentDay = $('#currentDay');
update();
setInterval(update, 1000);
});
// Add input to local storage-------------------------------------------------------//
$('.saveBtn').on('click', function () {
// Get the values
var hourinput = $(this).siblings('.hourinput').val();
var hour = $(this).parent().attr('id');
// Save data in local storage
localStorage.setItem(hour, hourinput);
});
$('#9 .hourinput').val(localStorage.getItem('9'));
$('#10 .hourinput').val(localStorage.getItem('10'));
$('#11 .hourinput').val(localStorage.getItem('11'));
$('#12 .hourinput').val(localStorage.getItem('12'));
$('#13 .hourinput').val(localStorage.getItem('13'));
$('#14 .hourinput').val(localStorage.getItem('14'));
$('#15 .hourinput').val(localStorage.getItem('15'));
$('#16 .hourinput').val(localStorage.getItem('16'));
$('#17 .hourinput').val(localStorage.getItem('17'));
Your .saveBtn elements have no siblings. You'll need to traverse up to the .row and then locate the elements / values within.
For example
$(".saveBtn").on("click", function () {
const row = $(this).closest(".row") // see https://api.jquery.com/closest/
// Get the values
const hourinput = row.find(".hourinput").val();
const hour = row.attr('id');
// Save data in local storage
localStorage.setItem(hour, hourinput);
});
FYI, your click event handler could be more efficient by listening at the container level (eg your <table>)
$("table#hours").on("click", ".row[id] .saveBtn", function() {
// etc
})
You should also make your buttons type="button" to make sure they don't accidentally submit any forms.

I can't collect in Javascript

I'm new to javascript, I want to place a code in my html page like the following, but I get a NaN error or no error. He just doesn't make the sums. My html page is in Turkish but I hope you will understand. Thanks in advance for your suggestions and help
in two different tables
<td id="Hizmet_Bedeli1">35</td>
<td id="Hizmet_Bedeli2">35</td>
it needs to show a total in another table
<th scope="row" class="align-middle" id="Ham_Toplam"> </th>
Here is the javascript:
{
var hb1= document.getElementById("Hizmet_Bedeli1").textContent; // If I use .value also, it doesn't work if I use .textContent as well.
var hb2= document.getElementById("Hizmet_Bedeli2").textContent; // .value de kullansam .textContent de kullansam düzelmiyor
var hizmet_toplam= parseInt(hb1) + parseInt(hb2); //parseInt de kullansam Number de kullansam Nan hatasıalıyorum... // If I use parseInt with Number, I get Nan error ...
document.getElementById("Ham_Toplam").innerHTML = hizmet_toplam;
}
I want to add the textContent of #Hizmet_Bedeli1 and #Hizmet_Bedeli2 together.
You are most probably not wrapping your tr and th tags in a table tag, which will cause your browser to not render the elements.
{
var hb1 = document.getElementById("Hizmet_Bedeli1").textContent;
var hb2 = document.getElementById("Hizmet_Bedeli2").textContent;
var hizmet_toplam = parseInt(hb1) + parseInt(hb2);
document.getElementById("Ham_Toplam").innerHTML = hizmet_toplam;
}
<table>
<tr>
<td id="Hizmet_Bedeli1">35</td>
<td id="Hizmet_Bedeli2">35</td>
<tr/>
<th scope="row" class="align-middle" id="Ham_Toplam"> </th>
</table>

Is there a way to remove and HTML element after six hours?

I have a picture with the word "NEW" over it to designate a new document that has been posted to our website. I would like to have jQuery remove the picture after 6 hours of it being posted. How would I go about doing this?
Here is the element:
<tr class="pointer">
<td>
<img class="germ" src="~/Image" width="40px" />
<i class="created" hidden="hidden">April 3, 2020 13:13:00</i>
Document Title
</td>
<td>PDF</td>
<td>March 2020</td>
</tr>
As you can see, I have a hidden <i> element that designates when the document was posted to the website. I need to remove the <img> tag 6 hours from the time in the <i> tag.
How can I do this using jQuery or JavaScript?
This would be better done server-side. The way you want to do it assumes that the user will have this same page up for 6+ hours, or come back to this page in the same state, which is pretty unlikely.
What I would do is add a property to the post for created and have it set a default time of Date.now(), and then have front end code look for whether that created value was less than 6 hours ago (1000 * 60 * 60 * 6 miliseconds).
If so, show the 'New' graphic. If not, don't.
Another way to do it so that you don't have to update server-side stuff that might be more set in stone is to have the default display for the "New" graphic to be true, then:
let createdTime = new Date(document.queryselector('i.hidden').textContent);
if (Date.now() - createdTime > (1000 * 60 * 60 * 6)){
//code to hide the "New" graphic
}
A little extra two cents for free: I would add an id attribute to that hidden i element to make sure you're selecting only that and not something else that may have the same class
Since you asked how to do this with JavaScript or JQuery, this is how.
I also included a 3-second example to show that it does work.
window.setTimeout(function() {
document.getElementById('sixHours').outerHTML = '';
}, 2160000);
window.setTimeout(function() {
document.getElementById('threeSeconds').outerHTML = '';
}, 3000);
<div id="sixHours">This will be removed after six hours</div>
<div id="threeSeconds">This will be removed after three seconds</div>
Keep in mind, that as soon as the page is refreshed, the timer will start over. If you want to avoid this and still have JavaScript handle it, you could have it removed at a definite time.
Edit
The snippet below will parse the date in expiration and find the milliseconds from that till now. Then like the snippet above, the remove element will get removed when the timer expires. 6 hours are added to the timer to make it expire 6 hours from the given time.
var expiration = Date.parse(document.getElementById('expiration').innerHTML);
var diff = expiration - Date.now();
window.setTimeout(function() {
document.getElementById('remove').outerHTML = '';
}, diff + 2160000);
//2160000ms = 6 hours
<div id="expiration">April 3, 2020 20:00:00</div>
<div id="remove">Will be removed by the date above</div>
Use setTimeout(), but bear in mind that people aren't likely going to sit at a single page for 6 hours meaning this will fail as soon as they navigate away. You'll have to change the time sent over every time they refresh.
const testing = true;
if (testing) {
// BEGIN - Fake date for testing
const tmpNow = new Date();
document.querySelector("i.created").innerHTML = tmpNow.toUTCString();
// END - Fake date for testing
}
const d = document.querySelector("i.created").innerHTML;
const dd = new Date(d);
if (testing) {
dd.setSeconds(dd.getSeconds() + 3);
} else {
dd.setHours(dd.getHours() + 6);
}
const ddd = dd.getTime();
const now = Date.now();
if (ddd < now) {
console.log("Too late");
}
const dt = Math.max(ddd - now, 0);
setTimeout(() => {
const img = document.querySelector("img.germ");
img.parentNode.removeChild(img);
}, dt);
<tr class="pointer">
<td>
<img class="germ" src="~/Image" width="40px" />
<i class="created" hidden="hidden">April 3, 2020 13:13:00</i> 03.21.2020 GOA - Alaska Businesses Now Eligible for SBA Economic Injury Disaster Loans (2)
</td>
<td>PDF</td>
<td>March 2020</td>
</tr>
You don't understand the problem here.
As R Greenstreet said it needs to be done server-side. You need a Create Post Date to be sent to UI.
Let's assume you have a JSON coming from a server where you can add createDate property of a post form bata base.
{createDate: date, name......}
You need to compare that date with Date.now()
Pseodu Code here:
if(createDate + 6 hours >= Date.now()) then hide your Icon.
You will need to use Date to convert the String into a Date Object:
new Date("April 3, 2020 13:13:00");
This will create a Date Object, yet since there is no Timezone Offset, the script might assume UTC. Your result might be:
"2020-04-03T13:13:00.000Z"
So consider specifying a Time Zone. Some browsers will assume the Users local Timezone.
$(function() {
function getDate(cObj, tz) {
if (tz == undefined) {
tz = "GMT-07:00";
}
var str = cObj.text().trim() + " " + tz;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var nDt = new Date(str);
console.log(str, nDt);
return nDt;
}
function getHoursPast(thn) {
// https://stackoverflow.com/questions/19225414/how-to-get-the-hours-difference-between-two-date-objects/19225463
var now = new Date();
return Math.floor(Math.abs(now - thn) / 36e5);
}
var hours = getHoursPast(getDate($(".created")));
console.log(hours + " have passed since", getDate($(".created")));
if (hours > 5) {
$(".germ").remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class="pointer">
<td>
<img class="germ" src="~/Image" width="40px" />
<!--
Would advise better format
Example: 2020-04-03T13:00.000-7:00
-->
<i class="created" hidden="hidden">April 3, 2020 13:13:00</i> Document Title
</td>
<td>PDF</td>
<td>March 2020</td>
</tr>
</table>
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
How to get the hours difference between two date objects?
Getting the client's timezone offset in JavaScript

Sorting with StupidTable JS and Date Columns

I am using StupidTable JS to sort my table columns. Works great. However most of my columns sort with
data-sort='string'
and now I have a DATE column I need to sort. Not sure how to do this. The info is fed from a database so I believe I need some function. The format each date is in is
dd-Mon-yyyy ex: 12-MAY-2015 or 25-JUL-2014
??
If you have control over the rendering of the HTML, you can sort on the timestamp while still displaying the pretty date.
https://github.com/joequery/Stupid-Table-Plugin#data-with-multiple-representationspredefined-order
Otherwise you'll need to create a custom sort function.
<table>
<thead>
<tr>
<th data-sort="string">Name</th>
<th data-sort="int">Birthday</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joe McCullough</td>
<td data-sort-value="672537600">April 25, 1991</td>
</tr>
<tr>
<td>Clint Dempsey</td>
<td data-sort-value="416016000">March 9, 1983</td>
</tr>
...
You could sort by int after converting the date string to an time-stamp (integer).
From the Stupid-table docs:
The plugin internally recognizes "int", "string", "string-ins" (case-insensitive) and "float", so simple data tables will take very little effort on your part.
var dateString = '12-MAY-2015'
var date = new Date(dateString).getTime()
// 1431385200000
Then use data-sort='int' on your th elements.
Or you could use a custom function:
These data types will be sufficient for many simple tables. However, if you need different data types for sorting, you can easily create your own!
<th data-sort="date">Date</th>
var table = $("table").stupidtable({
"date": function(a,b){
// Get these into date objects for comparison.
aDate = new Date(a);
bDate = new Date(b);
return aDate - bDate;
}
});
Note: above code not tested
I had the same problem, and fixed it as follows:
<td><span style="display:none;">20150512</span>12-MAY-2015</td>
Like this in PHP:
<? php
$ date = date_create (YOUR_DATABASE_FIELD);
echo '<td><span style="display: none;">'. date_format ($ date, "Ymd"). '</span>'. date_format ($ date, "d-M-Y"). '</td>';
I hope this help you!

Parse HTML table without IDs or CSS selectors in Node.js

This data is from an old system and the output is as is. We cannot add CSS selectors or IDs. Most of the examples online for node.js parsing involves parsing tables, rows, data with some ID or CSS classes but so far I haven't run into anything that can help parse the page below. This includes examples for JSDOM (AFAIK).
What I would like is to extract each of the rows into [fileName, link, size, dateTime] tuples on which I can then run some queries like what was the latest timestamp in the group, etc and then extract the filename and link - was thinking of using YQL. The alternating table row attributes is also making it a bit challenging. New to node.js so some of the terminology might be wrong. Any help will be appreciated.
Thanks.
<html>
<body>
<table width="100%" cellspacing="0" cellpadding="5" align="center">
<tr>
<td align="left"><font size="+1"><strong>Filename</strong></font></td>
<td align="center"><font size="+1"><strong>Size</strong></font></td>
<td align="right"><font size="+1"><strong>Last Modified</strong></font></td>
</tr>
<tr>
<td align="left">
<tt>file1.csv</tt></td>
<td align="right"><tt>86.6 kb</tt></td>
<td align="right"><tt>Fri, 21 Mar 2014 21:00:19 GMT</tt></td>
</tr>
<tr bgcolor="#eeeeee">
<td align="left">
<tt>file2.csv</tt></td>
<td align="right"><tt>20.7 kb</tt></td>
<td align="right"><tt>Fri, 21 Mar 2014 21:00:19 GMT</tt></td>
</tr>
<tr>
<td align="left">
<tt>file1.xml</tt></td>
<td align="right"><tt>266.5 kb</tt></td>
<td align="right"><tt>Fri, 21 Mar 2014 21:00:19 GMT</tt></td>
</tr>
<tr bgcolor="#eeeeee">
<td align="left">
<tt>file2.xml</tt></td>
<td align="right"><tt>27.2 kb</tt></td>
<td align="right"><tt>Fri, 21 Mar 2014 21:00:19 GMT</tt></td>
</tr>
</table>
</body>
</html>
Answer (thanks #Enragedmrt):
res.on('data', function(data) {
$ = cheerio.load(data.toString());
var data = [];
$('tr').each(function(i, tr){
var children = $(this).children();
var fileItem = children.eq(0);
var linkItem = children.eq(0).children().eq(0);
var lastModifiedItem = children.eq(2);
var row = {
"Filename": fileItem.text().trim(),
"Link": linkItem.attr("href"),
"LastModified": lastModifiedItem.text().trim()
};
data.push(row);
console.log(row);
});
});
I would suggest using Cheerio over JSDOM as it's significantly faster and more lightweight. That said, you'll need to do a for each loop grabbing up the 'tr' elements and subsequently their 'td' elements. Here's a rough example (My Node.js/Cheerio is rusty, but if you dig around in JQuery you can find some decent examples):
var data = [];
$('tr').each(function(i, tr){
var children = $(this).children();
var row = {
"Filename": children[0].text(),
"Size": children[1].text(),
"Last Modified": children[2].text()
};
data.push(row);
});
I don't know JSDom, but it sounds like it can parse a HTML document into a DOM (Document Object Model). From there it should be very possible to loop through the nodes and recognise them by tag name, attributes or position in the document, even if they don't have ids.
Googling for 5 seconds, please hold on...
JSDom's documentation on GitHub seems to confirm this. It shows jQuery-like selectors, like window.$("a.the-link").text(). So instead of adding a class, you can select for selectors like td, th, or probably even td[align="left"]. Using selectors like that, and convenient methods like .first and .each, to traverse over multiple results (like every row) you should be able to parse the document just fine, although it will of course be a bit more cumbersome than having convenient classnames for every different kind of cell.
I still don't think I'm a JSDom expert, but reading their project's main page for a couple of minutes already shows all the answers to your questions, and much more.
JSFiddle
var rawData = new Array();
var rows = document.getElementsByTagName('tr');
for(var cnt = 1; cnt < rows.length; cnt++) {
var cells = rows[cnt].getElementsByTagName('tt');
var row = [];
for (var count = 0; count < cells.length; count++) {
row.push(cells[count].innerText.trim());
}
rawData.push(row);
}
console.log(rawData);
Additional way
var cheerio = require('cheerio'),
cheerioTableparser = require('cheerio-tableparser');
res.on('data', function(data) {
$ = cheerio.load(data.toString());
cheerioTableparser($);
var data = [];
var array = $("table").parsetable(false, false, false)
array[0].forEach(function(d, i) {
var firstColumnHTMLCell = $("<div>" + array[0][i] + "</div>");
var fileItem = firstColumnHTMLCell.text().trim();
var linkItem = firstColumnHTMLCell.find("a").attr("href");
var lastModifiedItem = $("<div>" + array[2][i] + "</div>").text();
var row = {
"Filename": fileItem,
"Link": linkItem,
"LastModified": lastModifiedItem
};
data.push(row);
console.log(row);
})
});

Categories

Resources