I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () {
    $("#end").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 0,
        onSelect: function () {
            var start = $('#start');
            var startDate = $(this).datepicker('getDate');
            startDate.setDate(startDate.getDate() - 7);
            start.datepicker('option', 'minDate', startDate);
            start.datepicker('option', 'maxDate',$(this).datepicker('getDate'));
        }
    });
    $('#start').datepicker({
        dateFormat: "dd-M-yy"
    });
});

This block of code initializes datepickers in jQuery or Bootstrap with the END date set as the current date and the START date set as 7 days prior to the END date.

Answer №1

Creating Datepicker with jQuery

<input type="text" id="start">
<input type="text" id="end">

Jquery Code for Datepicker

$(document).ready(function () {
$("#end").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 0,
    onSelect: function () {
        var start = $('#start');
        var startDate = $(this).datepicker('getDate');
        startDate.setDate(startDate.getDate() - 7);
        start.datepicker('option', 'minDate', startDate);
        start.datepicker('option', 'maxDate', $(this).datepicker('getDate'));
    }
});
$('#start').datepicker({
    dateFormat: "dd-M-yy"
});
});

See the Demo here

This code snippet should help you to create a datepicker using jQuery.

Answer №2

Here is a solution that worked for my scenario:

 $(document).ready(function () {
        $("#start").val($.datepicker.formatDate("mm/dd/yy", new Date()));

        var startDateString = $('#start').val();
        var splitStartDate = startDateString.split("/");

        var startDate = new Date(splitStartDate[2], splitStartDate[0], splitStartDate[1]);
        var endDate = new Date();
        endDate.setDate(startDate.getDate() + 7);

        $("#end").val($.datepicker.formatDate("mm/dd/yy", endDate));
    });

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

Incorporating functions from another JavaScript file within an AJAX request

There's a function called _HideErrorBox() in the file 1.js that I want to use in the file 2.js within an AJAX call. I'm loading both 1.js and 2.js in a specific order. Here's the content of 1.js: var Calculations = function() { var _H ...

Animating a div in CSS3 to expand horizontally from left to right without affecting its original position

I am currently in the process of developing a calendar using HTML, CSS, and JavaScript. The main purpose of this calendar is to showcase upcoming and past events. However, I am facing difficulties in ensuring that my event blocks occupy the remaining space ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

Icon button with label positioned underneath - utilizing Font Awesome icons

I am looking to design a button that features a Font Awesome icon with text below it for a navigation menu. The goal is to achieve a layout similar to the icons found in the Microsoft ribbon. Additionally, I want to include an arrow below the button (simi ...

AddRegions does not function as expected

Basic code to initialize an App define(['marionette'],function (Marionette) { var MyApp = new Backbone.Marionette.Application(); MyApp.addInitializer(function(options) { // Add initialization logic here ...

Having trouble getting rounded-lg and rounded-md to work properly with Tailwind CSS - any ideas why?

I'm currently working with Next.js version 14.2.4 and tailwindcss version 3.4.1, and I've encountered an issue where rounded-lg and rounded-md classes are not applying any border radius. Oddly enough, other classes like rounded-xl and just rounde ...

Unspecified property in Vue.JS data object

Whenever I try to display my modal, an error pops up indicating that the property is not defined, even though I have clearly declared it in the Data(). It seems like there is a crucial aspect missing from my understanding of how everything functions... T ...

Transforming numerical values into text format when exporting data to Excel through datatables

I am encountering some issues when attempting to export my data as an Excel file using the datatables button. Specifically, when my data type is a number and starts with 0, this value disappears. Additionally, a (.) dot is automatically added as a delimit ...

Change the syntax to use async-await

Is it worth converting the syntax to async-await and how can I achieve this? // ---- UserRoutes ---- router.get('/user', middlewareJwt.jwtHandler, function (req, res) { UserService.get(req.userId, (user) => successCbk(res, 200, { ...

Socket connection in Vue not activating

I've been experimenting with incorporating Vue.js and sockets together, but I'm encountering an issue where my Vue application isn't receiving socket events. Despite following online tutorials, the example provided doesn't seem to work ...

Is it possible to disable the timeout for a single call using Axios?

I have set up an axios client instance in my application like this: const backendClient = axios.create({ baseURL: window['getConfig']?.url?.backend, httpsAgent: new https.Agent({ rejectUnauthorized: false }), timeout: window['getConfig ...

Can you point out the syntax error in my flex code?

I'm attempting to redesign my layout grid using flex. It seems that the flex code I commented out is incorrect, possibly due to an issue with setting the width in my .container class. The grid auto property adjusts the columns automatically within my ...

Exploring the Dependency Injection array in Angular directives

After some deliberation between using chaining or a variable to decide on which convention to follow, I made an interesting observation: //this works angular.module("myApp", []); angular.module('myApp', ['myApp.myD', 'myApp.myD1&a ...

Everything runs smoothly when initiating the API call through npm start, but unexpectedly crashes upon attempting to

Here is an API call located at http://localhost:9000/testAPI. Within the bin/www file: var port = normalizePort(process.env.PORT || '9000'); app.set('port', port); Inside the routes/index.js file: var express = require('express&a ...

Ensuring accurate data entry through form validation within a table format

I'm working with a textbox that is part of a table column. My goal is to make sure the entire column is not empty when the Ok button is clicked. If you have any suggestions on how I can achieve this, please let me know. var formatTableMandatoryVa ...

Extracting the input data from a JSON source

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Testing AJAX Requests ...

nodejs - pkg encountered an error: only one entry file or directory should be specified

I am currently facing issues with packing my simple cli node script using pkg. After running the command below: host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64 I encountered an error in the terminal: ...

What is the main focus of the active view in MVC2?

So, you can find my website at www.kristianbak.com. I've created a CSS class named activebutton, but I want it to dynamically change when another view is active. Right now, it's statically coded in the HTML (sitemaster). Does anyone have a clev ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Animating with JavaScript

I have a members button on my website that triggers a dropdown animation when clicked. However, the issue is that the animation occurs every time a page is loaded, even if the button is not clicked. I want the dropdown to only open when the button is click ...