document.getElementById(variable) Help! - javascript

I know it can be done but am having issues getting it to work. Basically I want to change the font color of a specific table cell based on a variable which changes daily, in effect highlighting the day of the week in a calendar. I know that a variable can be used to get the element id but what am I missing here? I have tried using a unique DIV inside each cell but get the same error - "Object Required". Thanks in advance.
Here is the code:
<style>
td#day1{color:white;}
td#day2{color:white;}
td#day3{color:white;}
td#day4{color:white;} etc..
<script type="text/javascript">
function calculate_date(){
currentTime = new Date();
day = currentTime.getDate();
return day;
}
function highlight_day() {
calculate_date();
today = 'day'+ day;
document.getElementById(today).style.color= "red";
}
document.onload(highlight_day());
</script>
</head>
<body>
SEPTEMBER
<table class="cal">
<tr>
<td id="day1">1</td><td id="day2">2</td><td id="day3">3</td><td id="day4">4</td>

This function is incorrect:
function highlight_day() {
calculate_date();
today = 'day'+ day;
document.getElementById(today).style.color= "red";
}
The 'day' variable is not set anywhere. You probably wanted this:
function highlight_day() {
var day = calculate_date();
var today = 'day'+ day;
document.getElementById(today).style.color= "red";
}

Change this line:
calculate_date();
to:
var day = calculate_date();
The error you are getting is because 'day' does not exist within the current scope.

Related

Pre-populate Form Field With The Internal Millisecond Clock From Javascript

I have a form on my website that I need to pre-populate with the current unix millisecond timestamp.
I do have another form field (in the same form) which successfully pre-populates the Date (Month, Day, Year) with the following code:
<div>DATE<br><input name="date" id="date"></div>
<script>
(function() {
var days = ['','','','','','',''];
var months =
['Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ]; };
Date.prototype.getDayName = function() {
return days[ this.getDay() ]; }; })();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
document.getElementById('date').value = day + ' ' + month + ' ' +
now.getDate() + ', ' + now.getFullYear();
</script>
However... I'm not having the same luck when attempting to pre-populate a second form field with the Unix Millisecond timestamp using this code:
<div>TIMESTAMP URL<br><input name="timeStampURL" id="timeStampURL"></div>
<script>
var d = new Date();
document.getElementById('timeStampURL').innerHTML = d.getTime();
</script>
I don't understand why the two codes behave differently that way, but any advice as to how to get that script to pre-populate the field would be appreciated.
Input elements don't have any content, so setting their innerHTML property does nothing. Your first function is setting the value attribute, so should your second:
function showTimeValue() {
document.getElementById('timeValue').value = Date.now();
}
window.onload = showTimeValue;
<input id="timeValue">
<button onclick="showTimeValue()">Update time value</button>
Each time you run the code, you'll get an updated value.

hide javascript dates in table

i have a form where the previous dates from today must be hidden in the first date picker and the second date picker must not show dates previous to the first selected date.
Date picker one
Date picker two
The form is working for the first row but i can't get the code to work for the other rows that follow when i "add" a new row.
Can anyone assist me with this Please?
here is my current code :
$(document).ready(function(){
function updateMinimumEndDate ()
{
var minimum = $('.DepartDate input').val();
var minSplit = [];
minSplit = minimum.split("/");
var newMin = (minSplit[2]+"-"+minSplit[0]+"-"+minSplit[1]);
$('.ReturnDate input').attr('min',newMin);
}
$('.DepartDate input').change(updateMinimumEndDate);
});
$(function() {
$(document).ready(function () {
var todaysDate = new Date();
var year = todaysDate.getFullYear();
var month = ("0" + (todaysDate.getMonth() + 1)).slice(-2);
var day = ("0" + todaysDate.getDate()).slice(-2);
var minDate = (year +"-"+ month +"-"+ day);
$('.DepartDate input').attr('min',minDate);
});
});
The problem is with the line
$('.DepartDate input').change(updateMinimumEndDate);
This needs to be in docReady. It also needs to use the jQuery function .on so that it will be triggered for new rows as they are added. I haven't checked this:
$('.DepartDate input').on('change', 'AnchorSelector', function() {updateMinimumEndDate())};
where AnchorSelector is a location which contains your form.

Jquery or Javascript - validate if current date is greater than due date

I have a site where users enter their tasks for the day and they are obligated to enter a due date and time (in this format: MM/DD/YYYY HH:MM, i.e. 03/07/2015 23:15). I was asked to find a way to highlight a TR cell when the due date time is coming up and when it's past due.
Example:
Highlight a TR in orange if the due date time is due in 15 mins.
Highlight a TR in red if the due date time has passed already.
So far, I've managed to find a way to get the current time using something like below:
jQuery(document).ready(function($) {
var dNow = new Date();
var current_time = ("0" + (dNow.getMonth()+1)).slice(-2) + '/' + ("0" + dNow.getDate()).slice(-2) + '/' + dNow.getFullYear() + ' ' + ("0" + dNow.getHours()).slice(-2) + ':' + ("0" + dNow.getMinutes()).slice(-2);
alert(current_time);
});
What I need help with is creating the logic to say if current_time > due_date_time then highlight red or if due_date_time is due in 15 minutes then highlight orange. How can I do this?
You can use the following jQuery for the purpose.
$('#timeTable tr td').each(function () {
var dtTd = new Date($(this).html());
var dtNew = new Date();
// 15 minutes is 900000 milliseconds
// getTime() doc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
if (dtTd.getTime() - dtNew.getTime() < 900000 && dtNew < dtTd) {
$(this).parent('tr').addClass('min15');
} else {
if (dtNew > dtTd) {
$(this).parent('tr').addClass('old');
}
}
});
Basically here is what is happening:
Go through each td in the table.
Get the text from td and convert it to date.
Check if the date is less than 15 minutes from now.
If it is less than 15 minutes, then apply min15 class to tr.
Else check if the date is older than now.
If it is old, then add old class to the tr.
jQuery is only being used to loop through each td, and to apply css classes easily. If you're not using jQuery anywhere else in your code, you could change it to vanilla JS.
Here is the jsFiddle for the same
I use moment.js for interacting with dates. It makes this kind of thing trivial:
// this line just sets the due date on the second row
// to 10 minutes from the current time so this demo will always work
// you dont need this line in your code
$('#myTable').find('tr').eq(2).find('td').eq(1).html( moment().add(10, 'minutes').format('L HH:mm') );
// loop through each row of the table
$('#myTable').find('tr').each(function(){
// get the cell with the date in it
var cell = $(this).find('td').eq(1);
var dueDate = $(cell).html();
// create a moment object from the entered time
dueDate = moment( dueDate );
// in the below line moment() creates a new moment object form the current date time
// much like new Date()
// .isAfter(dueDate) compares the current time to the due date
var isLate = moment().isAfter(dueDate); // returns true or false
if(isLate){
//$(cell).addClass('late'); // highlights just the cell
$(cell).parent().addClass('late'); // highlights the whole row
}
// get the current time then add 15 minutes
var nowPlus15Mins = moment().add(15, 'minutes')
// check if that time will be after the duedate
var isSoon = nowPlus15Mins.isAfter(dueDate); // returns true or false
// if its not late now, but will be in 15 minutes, highlight td
if(!isLate && isSoon){
//$(cell).addClass('soon'); // highlights just the cell
$(cell).parent().addClass('soon'); // highlights the whole row
}
});
.late{
background-color:red;
}
.soon{
background-color:orange;
}
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable" width="600" border="1">
<tbody>
<tr>
<th scope="col">Column 1</th>
<th scope="col">Column 2</th>
</tr>
<tr>
<td>Due Date</td>
<td>03/07/2015 23:15</td>
</tr>
<tr>
<td>Due Date</td>
<td>03/15/2015 23:15</td>
</tr>
</tbody>
</table>
Try
$("table tbody tr td").map(function(i, el) {
var due = 900000; // 15 minutes
return $(this).css("backgroundColor",
new Date($(this).text()).getTime() < $.now() // past due
? "red" // past due
: new Date($(this).text()).getTime() < $.now() + due // due within 15 minutes
? "orange" // due within 15 minutes
: "unset" // due beyond 15 minutes
)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<table>
<tbody>
<tr>
<td>03/08/2015 12:15:00</td>
</tr>
<tr>
<td>03/08/2015 12:30:00</td>
</tr>
<tr>
<td>03/08/2015 12:45:00</td>
</tr>
</tbody>
</table>
You can compare Date as simple as you can compare Numbers. Since that is a very easy use case, you can simply convert the users input to Date objects and compare them instead of using moment.js:
var due = new Date('03/07/2015 23:15'),
now = new Date();
if(now > due) {
// Due date is already exceeded
}
This will always work with full accuracy. Logic is to calculate difference in miliseconds and then get difference in minutes.
function CalculateDueDate(element){
var message = '';
var DueDt = new Date(DueDate);
var Today = new Date();
var MilliSecondDifference = Today - DueDt;
var DifferencePerMinute = 1000 * 60 * 24 * 365.26;
var MinutesDiff = MilliSecondDifference / DifferencePerMinute;
if (MinutesDiff > 15){
//Do what ever - 15 mins passed
}
else{
//Do what ever - with in 15 mins
}
}

JavaScript that prints date and time with a link won't work

I'm currently enrolled in a JavaScript class at my community college, and we're supposed to create a page with the following:
"Today's date is (date)"
"Kids Club"
"The time is (time)"
Then, I don't seem to get this part, the instructions state: "Have a link to the new kidsnew.htm page that contains the text "Go To Kids Club". Use onClick and widow.location to open kidsnew.htm.
Before switching, you should use the navigator object and the method to test for the name and version of the browser. Display the name and version of the browser with an alert box and advise the user to upgrade for better results with the new page if their browser is out of date.
The kidsnew page should contain an HTML form button that will take you back to the "kidsold.htm" page."
So. I assume that I'll need the browser verification, where you can find in the first part of the code. I don't get what else I'm supposed to be using, as we were not told of a "onClick" method in the chapter's were reading. Can anyone help me refine the code and get it to display as stated? I did most of it correctly, I think;
Here's my code:
<html>
<head>
<title>Kids Club</title>
<script type = "text/javascript" src = "brwsniff.js"></script>
<script type = "text/javascript">
<!-- hide me from older browsers>
//==============================Browser Info=================================
var browser_info = getBrowser();
var browser_name = browser_info[0];
var browser_version = browser_info[1];
var this_browser = "unknown";
if (browser_name == "msie")
{
if(browser_version < 5.5)
{
this_browser = "old Microsoft";
}
else
{
this_browser = "modern";
}
}
//end
if (browser_name == "netscape")
{
if (browser_version < 6.0){
this_browser = "old Netscape";
else
{
this_browser = "modern";
}
} //end
</script>
//=========================End Browser Info============================
//==========================Start Date Script============================
var date = new Date();
//new is keyword for object Date
//
//getting info from object Date
//
var month = date.getMonth();
var day = date.getDate();
var year = date.getYear();
var hour = date.getHours();
var minutes = date.getMinutes();
//january is month 0, think of arrays
//
month = month + 1;
//fix y2k
//
year = fixY2k(year);
//fix minutes by adding 0 infrotn if less than 10
//
minutes = fixTime(minutes);
var date_string = month + "/" + day + "/" + year;
var time_string = hour + ":" + minutes;
var date = "Today is " + date_string";
var time = "The time is " + time_string;
//y2k fix
//
function fixY2k(number) {
if (number < 1000){
number = number + 1900;
return number;
}
//time fixer
//
function fixTime(number){
if(number < 10) {
number = "0" + number;
}
return number;
}
//========================End Time Script==================================
// show me -->
</script>
</head>
<body>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(date);
</script>
//show me -->
<h1>Kids Club</h1>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(time);
</script>
//show me -->
</body>
</html>
Some comments:
> <script type = "text/javascript">
> <!-- hide me from older browsers>
That's rubbish, HTML comment delimiters were never needed to hide script element content, just remove them.
> var year = date.getYear();
You should use the getFullYear method, it avoids the two digit year issue.
> var date = "Today is " + date_string";
There is no need to declare date a second time. It's not harmful, just unnecessary. date started out as a Date object, now it's a string. That's not good programming style, just modify the existing date_string, e.g.
date_string = "Today is " + date_string";
In the body of the page you have:
> <script type = "text/javascript">
> <!-- hide me from older browsers
> document.write(date);
> </script>
> //show me -->
Note that the comment delimiters start inside the script element, then finish outside it. So the browser is left with invalid HTML and whatever happens next is a result of error correction (the same for the next script element too).
Fix that and you may have solved your problem.

Adding date countdown to jquery counter

Can someone help me with adding a date counting too to https://github.com/sophilabs/jquery-counter/blob/master/src/jquery.counter.js ?
The current counter is working fine with hour, minute and seconds. Its lacking only date. I am not an expert with it. Please help, thank you
I am not an expert but I think you can use this:
<script language='javascript' type= 'text/javascript>
function showdate()
{
var d = new date();
document.getElementById('date').innerHTML = d.toLocaleDateString();
}
</script>

Categories