How do I go about configuring the jQuery datepicker to only allow future dates to be selected

I have a text field that currently displays today's date along with a calendar icon. When the icon is clicked, a datepicker pops up with today's date preselected. What I'm trying to achieve is to have the datepicker open on a future date like 12/03/2012 when the calendar icon is clicked.

I can actually see the upcoming dates in my JSON response within Firebug:

[{"date":"01/05/2012","available":true},{"date":"05/05/2012","available":true}]

However, I'm struggling with how to refresh or update the calendar to display these forthcoming dates upon clicking the calendar icon.

Below is the code for my datepicker:

// Datepicker Options    
$(document).ready(function(){        
    $('#<%= ViewData.Model.name %>_DatePickerCalendar_<%= ViewData.Model.sector      %>').datepicker({
        changeYear: true,
        changeMonth: true,
        clearText: '',
        closeText: '',
        currentText: '',
        prevText: '«',
        nextText: '»',
        dateFormat: 'dd/mm/yy',         
        firstDay: 1,
        numberOfMonths: 2,
        minDate: 0,
        <% if(Model.name == "Flight") { %>
            maxDate: '+16m',
        <% } else { %>
            maxDate: new Date(<%=Model.maxDate.Year %>, <%=Model.maxDate.Month %> - 1,        <%=Model.maxDate.Day %>),
        <% } %>
        mandatory: true,
        showOn: 'both', 
        buttonImage: '/images/icons/ico-calendar.gif', 
        buttonImageOnly: true,
        buttonText: 'view calendar',
        changeFirstDay: false,            

            var date = new Date();
            if (sDate.value != "") 
                date = $.datepicker.parseDate('dd/mm/yy', sDate.value); 
            cbBeforeShow(date, '<%= ViewData.Model.name %>', '<%= ViewData.Model.sector %>', '<%= ConfigurationSettings.AppSettings["FutureAvailabilityYears"]%>');                               
        },
        beforeShowDay: cbCheckDayAvailable,            
        onChangeMonthYear: function(year, month, inst) {
            <%--/*
                When displaying multiple months with a set maxDate setting, and you   select the last month
                datepicker shows the max month last, this causes GetAvailability to not query the correct months
                changing the selected month to the previous means the correct availability is retrieved
            */--%>
            if (typeof inst.settings.maxDate === "object" &&
                month == (inst.settings.maxDate.getMonth() + 1) && 
                year == inst.settings.maxDate.getYear()) {
                month--;
            } 
            cbChangeMonthYear(year, month, '<%= ViewData.Model.name %>', '<%= ViewData.Model.sector %>', '<%= ConfigurationSettings.AppSettings["FutureAvailabilityYears"]%>')
        },                        
    <% } else { %>

        beforeShowDay: function(sDate) {
            cbCheckGreaterThanDateOut('<%= ViewData.Model.name %>'); 
        },
        beforeShowDay: function() {
            return [true, _gDatePickerCalendar.availDayClass ]
        },            
        onChangeMonthYear: null,

    <% } %>

        onClose: function(sDate) {
            cbOnClose('<%= ViewData.Model.name %>', '<%= ViewData.Model.name %>', '<%= ViewData.Model.sector %>');
        },              
        onSelect: function(sDate) {                
            cbOnSelect(sDate, '<%= ViewData.Model.name %>', <%= ViewData.Model.sector %>);                
        },
        defaultDate: new Date('15 October 2012')       
    });       
});

The JavaScript function triggered by the datepicker on "beforeShow" is as follows:

function cbBeforeShow(dDate, model, sector, futureAvailabilityMonths) {        

    _gDatePickerCalendar.GetAvailability(dDate, null, null, sector);
    setTimeout('$("#ui-datepicker-div")', 800);
    //checkForEmptyAvailabilityForMonth(dDate, null, null, model, sector, futureAvailabilityMonths);            
    $('#ui-datepicker-div').show();          
}

This is the AJAX call within the GetAvailability method:

$.ajax({
        url: _gDatePickerCalendar.availUrl,
        dataType: "json",
        async: false,
        success: function(data) {
            $.each(data, function(i, item) {
                if (item.date != "") {

                    var date = new Date(item.date.substring(6, 10), item.date.substring(3, 5) - 1, item.date.substring(0, 2));
                    _gDatePickerCalendar.availDays[i] = date;
                }
            });
        },
        complete: function() {
            var dd = new Date();
            alert("Just about to get a date from the array");
            dd = _gDatePickerCalendar.availDays[0];
            alert(dd);                                
        }
    });

Apologies for including so much code, but I'm really stuck on this issue :(

Answer №1

To accomplish this task, you can utilize the setDate method from jQueryUI Calendar within the beforeShow event as shown below:

beforeShow: function(input, inst) { 
    $(this).datepicker( "setDate" , new Date('01-01-2013'));
}

Here is a working example: http://jsfiddle.net/7HLn7/


Update:

The following corrections need to be made:

1.

var date = new Date(item.date.substring(6, 10), item.date.substring(3, 5) - 1, item.date.substring(0, 2));
Instead, it should be simply:

var date = new Date(item.date);

Ensure that your server method passes the date in 'yy/mm/dd' format for compatibility with US and UK locales.

2. What does this do?

setTimeout('$("#ui-datepicker-div")', 800);
. Refer to the setTimeout signature at https://developer.mozilla.org/en/DOM/window.setTimeout

  1. Additionally,

    var dd = new Date();
    alert("Just about to get a date from the array");
    dd = _gDatePickerCalendar.availDays[0];

This code snippet does not guarantee that dd will be a Date object. Learn about the differences between var in C# and JavaScript


You are almost there, just exercise some patience :)

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

When you start scrolling down, the JavaScript menu will cleverly disappear, only to re

I am facing an issue with my menu, which is a normal block-displayed div. There is another div with annotation above it. I want the menu to stick to the top as fixed when scrolling down, but immediately hide itself. The goal is for the menu to appear when ...

React project automatically refreshing when local server generates new files

I have developed a tool for developers that allows them to retrieve device data from a database for a specific time period, generate plots using matplotlib, save the plots locally, and display them on a webpage. The frontend is built using create-react-app ...

Building an ExtJS grid layout using JSON information

I want to clarify that my question is not about populating a grid with records from a json file. Rather, I am looking to create the actual columns of the grid using json. I want to save all the attributes of the columns, such as width, locked, and visibi ...

What is the best way to use checkboxes in VueJS to apply filters on a loop and display specific results?

I'm struggling with implementing filters using checkboxes on a list of results and could really use some assistance. Currently, only the 'All' option is working for applying any filtering logic. Here is how my HTML looks like with the filt ...

Unable to extract the ID URL from Next.js and integrate it with Axios

My attempt to execute a get request using axios has been unsuccessful due to the id const failing to load and being marked as undefined. Below is the code snippet: import Head from 'next/head' import axios from 'axios' import React, { u ...

Why does my React.js application still display outdated data from my Express server even after refreshing the webpage?

I have been working on a website using React.js and Express.js, following an online example to set up the basic code. I encountered an issue where the frontend did not update when I made a minor change to the array sent by Express.js. Express - users.js f ...

Validating the userid with jQuery before form submission

Currently, I am working on a form where I need to validate if the userID is already in use before allowing the user to submit it. After some research, I came across a solution on another website. However, when I tried to implement the code, I encountered ...

What are the steps to launching a node.js application on CyberPanel?

I have a node.js application developed and running on my server with cyberpanel installed. While I have found numerous examples of how to deploy a node application in cyberpanel, I am unsure about how to access it from the browser. Currently, my vHost con ...

Can a click event be implemented onto the controls of the anything slider?

Currently, on my website, I am utilizing the Anything slider and would like to implement a click event for the controls. However, I have encountered an issue as my event does not seem to trigger properly. Does anyone have any suggestions or ideas on how to ...

JavaScript multi-click navigation menu

I'm relatively new to JavaScript and I've been struggling with using multiple onClick attributes. While I have some code that works, I feel like there might be a simpler and cleaner solution to my problem. What I'm trying to achieve is a na ...

utilizing callback function for creating shopping cart feature within React

I'm in the process of creating an ecommerce website and implementing the add to cart functionality. I'm facing an issue where passing a callback function using props from a component to the parent component isn't working as expected. I' ...

How can I automatically update the content of a specific Div element when the page is loading using the Ajax load() function

This is the HTML code I have: <body onload="fun1()"> <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink" onclick="fun1()">Tab1</a></li> <li><a href="#" id="d_blink" onclick="f ...

Encountering issues while attempting to inject code into Microsoft Teams

Attempting to inject some JavaScript into Microsoft Teams using node integration. Success was achieved by adding an "app" folder with "package.json" and "index.js" into the "resources" folder of the Teams installatio ...

Is it true that all events in JavaScript go through capturing and bubbling phases?

My current project involves binding one eventListener to an <audio> element for the play event and another eventListener to its parent element for the same event. I've observed that the callback for the child element always gets executed, while ...

"Utilizing the useState hook to selectively update a portion of the state while keeping the remaining state unchanged

Hello there, I have a question. Is it possible to update just a portion of the state while keeping other parts the same in React? const stuff ={ 'a':'alpha', 'b':'beta' }; const [letter,setLetter]=useState(stuff); ...

Acquiring backend information to display in front-end using ReactJS

I receive data from the backend to present it in the following font: componentDidMount() { const response = this.props.store.privateImputationData; console.log(response); } When I check the console, it shows null. However, if I use a setTimeout, it w ...

Techniques for Grouping an Array of Objects by a Specific Value Key in Angular

I have the following array that needs to be grouped by section_name in HTML. Additionally, I need to first check if the length of the array values for section_name is greater than zero before displaying the results grouped by section_name. I hope my expl ...

Utilizing IonicSafeString for Alert Box Messages in Event Handling

.ts private async displayTermsOfServiceAlert(): Promise<void> { const alert = await this.alertController.create({ header: 'Updated Terms of Service', //problem lies here message: new IonicSafeString(`<ion-button i ...

Is it possible to create a cross-sectional view of a lens using the HTML5 canvas element?

I am interested in creating a visual representation of the cross section of a lens element. Typically, these elements consist of one or two circular surfaces (front and back) with a rim of arbitrary shape. My goal is to simply connect the front and back su ...

Using Node.js to leverage the async library for concurrently executing two tasks, then proceeding to start the final task after the first two have completed

Challenge Looking to run two tasks concurrently and then execute a third task after both are completed. I have been using the async library, which is functional but wondering if there is a more optimized approach. Tasks Task 1: readFileNames: Scans a di ...