Text Box Driven Date Selection using Asp.Net's Date Picker Control

I have 2 text boxes that accept dates from a calendar control. One is for the "From" date and the other is for the "To" date. Here's how I would like the dates to be handled:

For the first text box (From), it should only allow today's date or any previous date. However, the second text box (To) should also allow today's date but must not be earlier than the date selected in the first text box.

How can I achieve this in .NET? Below is my code snippet:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"   Inherits="Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.19.custom.css"  rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.19.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$("#txtfrom").datepicker({ maxDate:0 });
});
</script>

<script type="text/javascript">
$(function () {
    $("#txtto").datepicker({});
});
</script>


<style type="text/css">
.ui-datepicker { font-size:8pt !important}
</style>
</head>

<body>
<form id="form1" runat="server">
<div class="demo">
<b>From:</b> <asp:TextBox ID="txtfrom" runat="server" />
&nbsp &nbsp

<b>To:</b><asp:TextBox ID="txtto" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>

The first text box is functioning correctly. Can anyone assist with the coding for the second text box?

Answer №1

To set up your datepickers correctly, follow these steps:

        $("#txtFrom").datepicker({
            onSelect: function (selectedDate) {
                $("#txtTo").datepicker("option", "minDate", selectedDate);
            }
        });

        $("#txtTo").datepicker({
            onSelect: function (selectedDate) {
                $("#txtFrom").datepicker("option", "maxDate", selectedDate);
            }
        });

Essentially, this code snippet adjusts the minDate and maxDate options for txtFrom and txtTo when a date is selected in the datepicker.

Answer №2

To update your date selection functionality, follow these steps:

$(function () {
  $('[id$=txtTo]').datepicker();
  $('[id$=txtFrom]').datepicker();
});

If you want to set up date range restrictions, use the code below without braces:

$('[id$=txtFrom]').datepicker({
        onSelect: function (selectedDate) {
            $('[id$=txtTo]').datepicker("option", "minDate", selectedDate);
        }
    });

    $('[id$=txtFrom]').datepicker({
        onSelect: function (selectedDate) {
            $('[id$=txtFrom]').datepicker("option", "maxDate", selectedDate);
        }
    });

Answer №3

Eliminate the {} within

$("#txtto").datepicker({});

In my opinion.

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

Error: The property 'updateOne' cannot be read because it is undefined

I have been struggling to update an array in my MongoDB database, despite following the steps outlined in the official documentation. I can't seem to make it work. Can anyone provide assistance? I went through the official documentation, but unfortun ...

Why is inner HTML returning input/textbox instead of the value?

I need help extracting the value from an input/textbox within a table cell. Although the rest of my code is functioning correctly, I'm struggling to retrieve the value from this particular input element. I've attempted to access the value using ...

Securing Node function parameters in an asynchronous environment

I've been grappling with a pressing question lately, and I just can't seem to find a definitive answer. Let me share with you a Node function that I frequently use. It manages web requests and conducts some input/output operations: function han ...

In the world of Express, the res.write function showcases the magic of HTML elements contained within

Currently diving into web app development, I have ventured into using express and implemented the following code snippet: app.post("/", function(req, res) { var crypto = req.body.crypto; var fiat = req.body.fiat; var amount = req.body.amount; va ...

The functionality of scope.$observe is unavailable within an AngularJS Directive

Consider the snippet below: appDirectives.directive('drFadeHighlight', ['$animate', '$timeout', function ($animate, $timeout) { return { scope: { isWatchObject: '=' }, restric ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

Is there a way to sort an elastic query using JavaScript?

I'm trying to modify my elastic query by adding and removing items from an array. In the array below, I want to remove the element that contains 'item2'. How can I achieve this by checking if the key 'item2' exists and then deletin ...

Skip ahead button for fast forwarding html5 video

One of the features in my video player is a skip button that allows users to jump to the end of the video. Below is the HTML code for the video player: <video id="video1" style="height: 100%" class="video-js vjs-default-skin" controls muted autoplay=" ...

Creating a dynamic webpage using Javascript that responds to user clicks on page links

I am interested in the process of inserting JavaScript objects from a JSON file in order to dynamically create a unique page based on a user's clicked link. This concept is similar to having a wildcard page in popular frameworks like Laravel or Django ...

Does implementing a product listing with filter, sorting, and search options through Ajax violate any REST principles?

As I work on creating a product listing library for a web application, it's crucial to incorporate filter, search, and sort functionalities. A web service is available that can fetch results based on these parameters, including page number and product ...

Choosing to maintain an open server connection instead of regularly requesting updates

Currently, I am in the process of developing an innovative online presentation tool. Let's dive into a hypothetical situation: Imagine one person is presenting while another connects to view this presentation. >> How can we ensure that the vie ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...

The socket context provider seems to be malfunctioning within the component

One day, I decided to create a new context file called socket.tsx: import React, { createContext } from "react"; import { io, Socket } from "socket.io-client"; const socket = io("http://localhost:3000", { reconnectionDela ...

How do I implement using separate properties for the URL and display link in a custom Url DisplayTemplate using MVC?

Within my shared folder, I have created a DisplayTemplate folder containing a Url view with the following code: <a href="@ViewData.Model" target="_blank"> @ViewData.Model</a> Here is an example of what properties in my Employee class look lik ...

Error message: Electron is unable to read properties of undefined, specifically the property 'receive'. Furthermore, the IPC is unable to receive arguments that were sent through an HTML iframe

I am currently working on passing light mode and language data from ipcMain to ipcRenderer via my preload script: Preload.js: const { contextBridge, ipcRenderer } = require("electron"); const ipc = { render: { send: ["mainMenuUpdate& ...

Despite the unconsumedBufferLength being 0, DataReader.loadAsync is still being completed

Working on UWP WinRT, I'm dealing with JSON stream consumption using the following code: async function connect() { let stream: MSStream; return new CancellableContext<void>( async (context) => { stream ...

Tips for choosing a class with a leading space in the name

Struggling with an issue here. I'm attempting to adjust the CSS of a specific div element that is being created dynamically. The current output looks something like this: <div class=" class-name"></div> It seems there is an extra space b ...

The combination of PHP and JavaScript looping is struggling to produce the correct sequence of results

for(var i=0; i<participantNum; i++){ studentID = $('#txtID'+(i+1)).val(); alert(studentID); //implementing a PHP function to validate each student's ID by making AJAX calls request("http://localhost/lastOrientation/2_regis ...

Retrieve every HTML element that is currently visible on the screen as a result

I have a dynamic HTML table that updates frequently, with the potential for over 1000 rows. Instead of replacing the entire table each time it updates, I am exploring options to only update the visible rows. My initial approach involved iterating through ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...