What is the best way to increase the Date in the second TextBox by one day after the first TextBox's date?

There are two TextBox fields on a page. The requirement is that when a user selects a date from the first TextBox, the second TextBox should automatically display the next day's date (disable any previous dates). For example: If the user selects 2020-12-29 in the first TextBox, the minimum allowable date for the second TextBox should be 2020-12-30.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var today = new Date();
        var month = ('0' + (today.getMonth() + 1)).slice(-2);
        var day = ('0' + today.getDate()).slice(-2);
        var year = today.getFullYear();
        var date = year + '-' + month + '-' + day;
        $('[id*=txt1]').attr('min', date);
    });
</script>
<asp:TextBox ID="txt1" runat="server" TextMode="Date"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server" TextMode="Date"></asp:TextBox>

I'm struggling to implement the functionality for the second TextBox using JavaScript alone. However, I am open to suggestions for implementing it using C# as well.

Answer №1

Give this a shot:

    <script type="text/javascript">
        $(function () {
            var today = new Date();
            var month = ('0' + (today.getMonth() + 1)).slice(-2);
            var day = ('0' + today.getDate()).slice(-2);
            var year = today.getFullYear();
            var date = year + '-' + month + '-' + day;
            $('[id*=inputField]').attr('min', date);


            $('[id*=inputField]').change((e) => {
                var day = 60 * 60 * 24 * 1000;

                let date1Arr = $('[id*=inputField]').val().split(/\D/);
                let updatedDate = new Date(date1Arr[0], date1Arr[1], date1Arr[2]);
                updatedDate = new Date(updatedDate.getTime() + day);
                let yyyy = updatedDate.getFullYear();
                let mm = updatedDate.getMonth() + 1;
                let dd = updatedDate.getDate();

                if (mm < 10)
                    mm = '0' + mm;
                if (dd < 10)
                    dd = '0' + dd;
                let updatedDateText = [yyyy, mm,dd].join('-');
                $('[id*=outputField]').attr('min', updatedDateText);
            });
        });
    </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

Are all modules loaded when exporting from index.ts?

In my React + TypeScript project, I have multiple exports in my index.ts file. When I import things from this file, I sometimes encounter circular dependencies, especially when writing tests with Jest. My question is, when I import items from index.ts file ...

Dealing with an endless loop caused by a promise in AngularJS's ui router $stateChangeStart event

I am currently working on implementing authentication in my Angular application and I want to redirect to an external URL when a user is not logged in (based on a $http.get request). However, I seem to be stuck in an infinite loop when using event.prevent ...

Is it more efficient to store the DataSet in Session/Cache or fetch it from the Database each time it is needed?

Crafting a DataSet involves a considerable amount of coding work. I'm unsure about the recommended industry practice for managing data requests from multiple ASP.NET pages. Should I rely on cache/session to transmit the DataSet between pages or should ...

Date-based calendar created from data in two different tables

I am looking for a way to display the Start Date and End Date from two tables, Confirm_orders and Tentative Orders, in a calendar on my .aspx page. Is there a method for implementing these dates in the calendar? My goal is to have the event dates represe ...

Generate a selection of complementary, triadic, and monochromatic color palettes using just one hex color code

My goal is to generate three unique color palettes based on a single hex/rgb value given by the user. The first palette will feature the complementary color of the initial input, followed by a full range of colors in subsequent palettes. I aim to expand be ...

Loop through page.evaluate in Nodejs

Currently, I am attempting to utilize the for-of looping method in order to iterate through an array of URLs and apply them with the page.evaluate function from the puppeteer library. To simplify my process, I will share a snippet of my code (with a sing ...

The Node.js promise failure can be unpredictable, despite being properly managed

In my journey to master MongoDB, I am currently exploring its capabilities by building a basic blog application. However, I have encountered an issue with the code responsible for saving blog posts - it seems to be inconsistent in its success rate, sometim ...

Mandrill: Sorry, the server seems to be experiencing some technical difficulties with a 500 internal server error

I have utilized the following code snippet to send emails using Mandrill: public bool sendMessage(string from, List<To> to, string subject, string body,out string rsText) { var host = "https://mandrillapp.com/api/1.0"; if (k ...

When using the Node.js drive API, setting the emailMessage while creating a permission does not trigger the sending of an

Working with Node.js and the googleapis v61.0.0 client to utilize drive api v3. Strange issue encountered when attempting to create a permission: setting the 'emailMessage' param to anything other than an empty string (or not specifying it at all ...

The attempted upgrade to Highcharts 11 within the Angular App was unsuccessful due to a lack of loader capable of handling the

An issue has been detected in the highcharts.js file located in ./node_modules/highcharts/ at line 8:5207. The module parsing failed due to an unexpected token found at this position. To resolve this error, you may need to set up a suitable loader to proce ...

What are the steps for performing projection in TypeScript?

Looking to fill up the orders array, which consists of objects of type Order. The desired output is orders=[{id:1,qt:4},{id:2, qt:2},{id:3,qt:2}]. How can I achieve this using TypeScript? I am new to this language. export class Product { constructor(publ ...

Having trouble with transferring image blob to AWS S3 with node.js & angular

I'm having trouble uploading my images to AWS S3 { [InvalidParameterType: Expected params.Body to be a string, Buffer, Stream, Blob, or typed array object] message: 'Expected params.Body to be a string, Buffer, Stream, Blob, or typed arr ...

Is async/await necessary even if the outcome is not important to me?

Imagine I have an API call that performs X and I convert it into asynchronous code using async/await: export default async (req: NextApiRequest, res: NextApiResponse) => { let success = await sendEmail({ //... }); return res.status(200) ...

Adding a class to radio buttons with a specific label using jQuery

As of now, I am utilizing jQuery to apply or remove a class when a radio button is selected. However, the issue arises when it checks all radio buttons, resulting in CSS being added to only one radio button. My HTML layout consists of rows containing eith ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

AngularJS not displaying loader during AJAX request

While utilizing ajax requests with $http, there seems to be a delay due to the server operation taking longer than expected. I have implemented a loader to display while processing the request, but unfortunately it is not showing up on the page. Even after ...

Sending PHP array data to a JavaScript function

I am attempting to establish a connection with a database using PHP and dynamically display the results using JavaScript. Here is my approach - <?php function mainMenu($q){ $res=array();; $q->setFetchMode(PDO::FETCH_NUM); while($r = $q->fetch ...

The organization of the SortedDictionary<Of <(<'TKey, TValue>)>)>..::..Enumerator type's syntax

As stated on MSDN: SortedDictionary<(Of <(<'TKey, TValue>)>)>..::..Enumerator The return type in .Net 4.0 of the SortedDictionary's GetEnumerator method seems complicated and unfamiliar. While I understand typical generics lik ...

A different way to add a child element in JavaScript without using

Is there a way to insert a node as a child element at position 0, replacing any existing child nodes rather than appending? What function can I use to ensure cross-browser compatibility for this operation? ...

Leverage a JavaScript function to manipulate the behavior of the browser's back button

Is there a way to trigger the Javascript function "backPrev(-1)" when the back button of the browser is clicked? Appreciate any help, thank you. ...