Implementing a Timer on an HTML Page with JavaScript

I am looking to add a timer to my HTML page using JavaScript. The timer should get the selected date and time from an input field <input type="date" /> and control it. If the time difference between the current time and the selected time is less than 1 day, the timer should display an alert message. Can someone guide me on how to compare the current time with the selected time? Thank you for all the help.

function add() {
  var num = document.getElementById("t1").rows.length;
  console.log(num);
  var x = document.createElement("tr");

  var a = document.createElement("td");
  var anode = document.createTextNode(num + '.');
  a.appendChild(anode);
  x.appendChild(a);

  a = document.createElement("td");
  anode = document.createElement("input");
  var b = document.createAttribute("type");
  b.value = "checkbox";
  anode.setAttributeNode(b);
  a.appendChild(anode);
  x.appendChild(a);

  a = document.createElement("td");
  anode = document.createElement("input")
  var b = document.createAttribute("type");
  b.value = "date";
  anode.setAttributeNode(b);
  a.appendChild(anode);
  x.appendChild(a);

  a = document.createElement("td");
  anode = document.createElement("input");
  b = document.createAttribute("type");
  b.value = "text";
  anode.setAttributeNode(b);
  a.appendChild(anode);
  x.appendChild(a);

  a = document.createElement("td");
  anode = document.createElement('input');
  anode.setAttribute('type', 'button');
  anode.setAttribute('value', 'Delete Row');
  anode.setAttribute('onclick', 'deleteRow(this)');
  a.appendChild(anode);
  x.appendChild(a);
  document.getElementById("t1").appendChild(x);
}

function deleteRow(e, v) {
  var tr = e.parentElement.parentElement;
  var tbl = e.parentElement.parentElement.parentElement;
  tbl.removeChild(tr);
}
table {
  border-collapse: collapse;
  margin: 10px;
}

table,
td,
th {
  border: 1px solid black;
  padding: 10px;
}
<table id="t1">
  <tr>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th>
      <input style="padding:10px" type="button" value="Add Row" onclick="add()" />
    </th>
  </tr>

  <tr>
    <td>1.</td>
    <td>
      <input type="checkbox" />
    </td>
    <td>
      <input type="date" />
    </td>
    <td>
      <input type="text" />
    </td>
    <td>
      <input type="button" value="Delete Row" onclick="deleteRow(this)" />
    </td>

  </tr>
</table>

Answer №1

I believe I have understood your query correctly - it seems like you are interested in informing the user if the date they choose is x amount of days after (or before? This part was not entirely clear) the current date.

If that is indeed what you are looking for, then this solution should meet your needs. I have set the threshold to 2 days before or after the present date - so if there is a difference of at least +/- 2 days from the current date, an alert will be triggered.

This function activates when the value of the date input is modified

$(document).ready( function() {

  // When date input value changes...
  $('.date').change( function() {
  
    // Create Date objects for the current date and the user-selected date
    var today = new Date();
    var selectedDate = new Date( $(this).val() );
    
    // Use UTC to avoid issues with daylight saving time, etc.
    var milliseconds = 86400000;
    var utcToday = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
    var utcSelected = Date.UTC(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate());
    
    // Calculate the difference (in days) between the dates
    var result = Math.floor((utcSelected - utcToday) / milliseconds);
    
    // Check the result and show alert if there is at least a +/- 2 days gap from the current date
    if(result >= 2 || result <= -2)
      alert("There is a 2+ days difference between the current date and the selected date");
  });
  
});
<!-- Include jQuery... assuming this is acceptable since you used jQuery tags -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Added class "date" to the input field -->
<input class="date" type="date" />

Answer №2

If you want to introduce a delay before executing a function, setTimeout is the way to go. In this example, myFunction will be called after 3 seconds.

<button onclick="setTimeout(myFunction, 3000)">Give it a shot</button>

<script>
function myFunction() {
    alert('Greetings');
 }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Non-functioning function within object

this is a unique object var Manager = (function () { var self = this; self.fetch = function (request, response) { response.send({ message: 'Data fetched successfully' }); } return self; })() module.ex ...

The hover effect is not activated by the mouse movement event

I previously encountered an issue related to flickering with an absolute div when moving my mouse, which I managed to resolve by increasing the distance between my mouse pointer and the div. Now, I am working on the next phase of my project: My goal is t ...

Is it possible for a navbar in CSS to collapse based on its width?

At the moment, I am utilizing Bootstrap v3.3.6 and jQuery v1.9.1. My current project involves a horizontal navbar that collapses once it reaches a specific screen resolution. I am pleased with how this feature operates and wish to maintain the same breakpo ...

Aligning navigation text in a grid layout

I am currently working on evenly distributing my 8 navigation links across the navigation bar. Below is the HTML code for my navigation: <nav> <ul class="nav"> <li><a href="index.html">Home</a></li> < ...

Populate a dropdown menu in jQuery with options generated from an array

I'm planning to include 4 dropdowns in my project. My approach involves creating 3 arrays (the first dropdown is hardcoded). The idea is that based on the selection made in the first array, the options for the second dropdown will be populated. How ca ...

Efficiently adding values to a variable with the forEach method

I'm encountering an issue with displaying data from a JSON file similar to the one below: Currently, "checked" is set to null. I aim to update it to true within the steps array using a forEach loop. JSON data snippet: { "id": 4, "process": { ...

An effective method for retrieving the version from package.json

I am currently in the process of developing an SDK that will soon be available on npm. One of the requirements for this SDK is to deliver its version to the client. My goal is to have this version match the one specified in the package.json file. However ...

Eliminate the table background in a single cell

Apologies if the title is not very descriptive, I couldn't find the right words to use. Below is the table in question. https://i.sstatic.net/LHwbG.png I'm looking to remove the white border (background of the table) from just the upper-left ce ...

Encountering a node-gyp error during the deployment of a Rails 6 application with a Vue app on Heroku

I'm running into an issue when trying to deploy my Rails 6 app with Vue on Heroku. The error I'm getting is as follows: [4/4] Building fresh packages... error /tmp/build_c242c7d78580af478535f5a344ff701e/node_modules/fibers: Command failed. ...

Delete the following td when the mouse hovers over it

How can I modify my code to remove the next td on mouseenter of a particular td? Currently, my code is removing the first occurrence of mouseenter on any td and the current mouseover td. Here is the snippet of my code. Can anyone help me identify what&apos ...

What is the significance of utilizing response.json() for accessing JSON objects on both the server and client sides?

Just starting out with the MEAN stack, I've included my API code below where I'm using res.json(random) to send a random password. module.exports.changePass = function (req, res) { console.log(req.body.email) db.user.find({ where: { name: ...

Utilize a class within a Framer Motion element to incorporate animations or set initial properties

Is there a way to apply a class using Framer Motion tag in the animate and initial props? Here's an example: <motion.div initial={{ className: 'hidden' }} animate={{ className: 'visible' }} > <div>yo</div> & ...

Incorporating Products from an Iframe into the Cart on Woocommerce

I recently set up a store using WooCommerce, and I have a unique situation where my customizable products are displayed within an iframe. The "add to cart" button is also contained in this iframe. Whenever I click on the Add to Cart button, I receive a mes ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

Enhance Your Button with CSS3 Animation

While experimenting with CSS3 animations, I encountered a challenge when trying to apply an animation to a button upon clicking. The desired effect was for the button to zoom in, spin, and then zoom out, giving the appearance of flying off the screen. Surp ...

Struggling to securely post data to an Express server by hashing passwords with bcrypt?

I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing. const createNewUser = (data) => { return new Promise(async (resolve, ...

Add a jQuery click function within a loop indefinitely

Hello there, I have a simple loop set up in PHP and I am trying to figure out how to create an event that triggers whenever the user clicks on any line generated by this loop. Here's my basic PHP while loop: <?php $x = 1; while($x <= 5) { ...

Chrome will automatically retry an AJAX POST request if it times out after 10 seconds

I am in the process of creating a React JavaScript application using a back end powered by Node.js and Express. The software versions being used are as follows: React: ^16.0.0 Node: v8.0.0 Express: ^4.14.0 Chrome: Version 63.0.3239.84 (Official Build) (64 ...

Ways to obtain a referrer URL in Angular 4

Seeking a way to obtain the referrer URL in Angular 4. For instance, if my Angular website is example.com and it is visited from another PHP page like domaintwo.com/checkout.php, how can I detect the referring URL (domaintwo.com/checkout.php) on my Angul ...

Resizing a d3 graph for various screen resolutions

Looking to create a dynamic dashboard in Angular, I found a code snippet for a gauge chart at this link. Here is an example of how my HTML file appears: <div fxLayout="row" fxLayoutAlign="space-around center" > <div fxFlex='33%'> ...