Adjust the knock date to be two days earlier than the delivery date using vue.js

I am brand new to the world of vue.js and I have encountered a question. My form includes two date input fields labeled as Delivery date and Knock date.

My goal is to automatically set the knock date to be two days before the delivery date. For instance, if the delivery date is 20/9/2021, then the knock date should be 18/9/2021.

I would appreciate any guidance on how to achieve this functionality in vue.js.

Here are the form fields provided below:

<template> 
<form>   
<label for="">PO Delivery Date</label>
<input
    class="form-control"
    type="date"
    v-model="PO_DeliveryData"
    v-validate="'required'"
    placeholder="PO Delivery Date"
/><br />
    
<label for="">Knock Date</label>
<input
   class="form-control"
   type="date"
   v-model="knock_Date"
   v-validate="'required'"
   placeholder="Knock Date"
/><br />
</form>
</template>

<script>
export defaults:{

}
</script>

Answer №1

Check out the code snippet below:

new Vue({
  el: '#demo',
  data() {
    return {
      PO_DeliveryData: '',
      knock_Date: ''
    }
  },
  watch: {
    PO_DeliveryData() {
      let d = new Date(this.PO_DeliveryData);
      d.setDate(d.getDate() - 2);
      this.knock_Date = d.toISOString().slice(0, 10)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo"> 
  <form>   
    <label for="">PO Delivery Date</label>
    <input
        class="form-control"
        type="date"
        v-model="PO_DeliveryData"
        placeholder="PO Delivery Date"
    /><br />

    <label for="">Knock Date</label>
    <input
       class="form-control"
       type="date"
       v-model="knock_Date"
       placeholder="Knock Date"
    /><br />
  </form>
</div>

Answer №2

One way to easily compute dates in JavaScript is by using momentjs library

<template>
  <form>
    <label for="">PO Delivery Date</label>
    <input
      v-model="deliveryDate"
      class="form-control"
      type="date"
      placeholder="PO Delivery Date"
    /><br />

    <label for="">Knock Date</label>
    <input
      :value="knockDate"
      class="form-control"
      type="date"
      placeholder="Knock Date"
    />

    <pre>deliveryDate: {{ deliveryDate }}</pre>
    <pre>knockDate: {{ knockDate }}</pre>
  </form>
</template>

<script>
import moment from "moment";

export default {
  name: "App",
  data() {
    return {
      deliveryDate: "",
      knockDate: "",
    };
  },
  watch: {
    deliveryDate(val) {
      if (val) {
        this.knockDate = moment(val, "YYYY-MM-DD")
          .subtract(2, "day")
          .format("YYYY-MM-DD");
      } else {
        this.knockDate = "";
      }
    },
  },
};
</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

What is the most efficient and hygienic method for storing text content in JavaScript/DOM?

Typically, I encounter version 1 in most cases. However, some of the open source projects I am involved with utilize version 2, and I have also utilized version 3 previously. Does anyone have a more sophisticated solution that is possibly more scalable? V ...

Even though I have properly set up the express.static() function and ensured that the path is correct, my initial app is still not serving the

Just like the title suggests, I am venturing into building my first node app and have come across an issue. Everything was working perfectly yesterday. However, when I booted up my PC today, I received the error message "Resource interpreted as Stylesheet ...

No alteration in image appearance post downloading the file (VueJs and FileReader)

I have a file input where I can upload images. Once an image is loaded, I set the value of my data property "imgSrc" methods:{ setImage(e){ let file = e.target.files[0]; let isValidImageWidthAndHeight = true; let $self = this; let reader ...

When I attempt to access localhost/laravel/public/my_page, the page appears completely blank without displaying any errors

In my Laravel project, all pages function properly when using php artisan serve. However, some pages encounter issues when not using artisan serve. For instance, when I access localhost:8000/my_page, the page loads successfully. But if I try to access lo ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

Displaying the order number in an alert notification once the form has been successfully submitted and retrieved from the database

After successfully displaying an alert box message confirming that my form has been submitted, I now want to enhance it by adding the order number retrieved from my database. The current code snippet in my PHP script displays a basic alert as shown below: ...

Fading effect malfunctioning

I created a basic CSS box and am attempting to fade it by adjusting its opacity dynamically using the setInterval object. Click here for the code on jsFiddle CSS #box { margin:0px auto; margin-top:10px; height:50px; width:50px; background:black; } JAVA ...

The initial click does not trigger a state update in React

I attempted to create a straightforward system for displaying data with two sorting buttons (ascending & descending). My approach involved fetching and displaying data from an array using the map method. In a separate component file, I utilized useEffect ...

What is the best way to access and modify a nested object within a complex object containing an array of objects?

I've got the course structure all sorted out, but I'm struggling to understand how to retrieve a lesson object by its ID and also update a lesson object with new property values. If anyone could provide some guidance on the right approach, it wo ...

Is there a newer alternative to the jQuery UI Draggable component available?

In search of draggable/sortable functionality for my .NET Razor Pages application. Came across the jQuery UI Draggable/Sortable component which I've used years ago with success. However, it's mentioned on the download page that the component is ...

Gather data from various textboxes and combine them into a unified string with the help of JavaScript

I am currently facing a challenge where I need to extract the values from multiple textboxes and combine them into a single string. This string will then be sent to my PHP processing page for insertion into a database table. The textboxes mentioned above ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

Sending element information to jQuery.post callback function

My goal is to have this.item of an instance of the class filled with data received through the jQuery.post successor function. Currently, I am achieving this by using another user-defined function to set this.item with the received data. Query: Is there a ...

Guide to capturing mouse drag coordinates using JavaScript within a JSP page

My task is to record the starting coordinates (x,y) and ending coordinates (x,y) of a mouse event. For example, on an HTML page with an image, users should be able to select a specific area by dragging the mouse. Therefore, I need to capture the coordinat ...

Showing all steps in introJS allows for a comprehensive walkthrough of the user interface

Can all the introJS step numbers be displayed simultaneously to show all areas of the page with explanations, without highlighting their associated elements or tooltips? Could these numbers be made clickable so that users can choose to view an explanatio ...

Steps for verifying repetitive names in input fields

I am experiencing difficulty trying to implement the same validation across multiple tabs within a form. The validation seems to be working in one tab, but not in the others. The start date must always be before the end date My goal is to validate fields ...

Learn the process of creating test cases using `ava` for the following code snippet

const TimeToEvent = minutes => { const oneMinute = 1; const minutesInAnHour = 60; if (minutes <= oneMinute) { return "in just 1 minute"; } if (minutes < minutesInOneHour) { return "in mere&quo ...

Troubleshooting HTTP requests in Angular JS when dealing with nested scopes

This particular question is derived from a previous answer found at this link. In my current scenario, I am attempting to initiate an http request where one of the data values that needs to be sent is represented in the view as {{selectedCountry.shippin ...

What are all the characteristics of the object's objects?

After spending the entire day searching for answers, I've come to the conclusion that I might be looking in the wrong place. Coming from a background in .NET development, my mindset revolves around objects having keys and corresponding values. In Visu ...