Selecting Departure and Return Dates using jQuery UI Datepicker

I'm working on creating two DatePicker fields for selecting departing and returning dates. For instance, if a user is planning a 5-night holiday, the initial dates displayed would be:

01/12/2010 | Calendar Icon 07/12/2010 | Calendar Icon

With the departing date field allowing selection of any future date, while the returning date field restricts selection to dates that are five nights after the departing date.

I've made progress in achieving this functionality by referring to various Stack Overflow articles. Below is the code snippet I am using:

$().ready(function() {
    $('.dDate, .rDate').datepicker({
        showOn: 'both',
        buttonImage: "<?=$http?>layout_images/calendar.gif",
        buttonImageOnly: true,
        beforeShow: customRange,
        buttonText: 'Open Calendar',
        firstDay: 1,
        dateFormat: 'D d M yy',
        onSelect: function(date) {
            date = $(this).datepicker('getDate');
            $('#returningdate').val($.datepicker.formatDate('D d M yy', date));
        }
    });
});

function customRange(a) {
    var b = new Date();
    var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
    if (a.id == 'returningdate') {
        if ($('.dDate').datepicker('getDate') != null) {
            c = $('.dDate').datepicker('getDate');
        }
    }
    return {
        minDate: c
    }
}

The current code behavior is as follows:

After selecting 01/12/2010 in the departing date field, the returning date field automatically shows 01/12/2010.

Departing date allows selection of any date (including today), and the return date cannot be earlier than 01/12/2010.

However, the desired behavior is for the system to automatically add 5 nights to the selected departing date (01/12/2010) and set the returning date to 07/12/2010, restricting selection of dates prior to that.

Is there an easy way to modify the existing code to achieve this functionality?

Thanks,

Quintin Hobson

Answer №1

This is the unique solution I uncovered:

    $(document).ready(function() {
        $('.dDate, .rDate').datepicker({
            showOn: 'both',
            buttonImage: '<?=$http?>layout_images/calendar.gif',
            buttonImageOnly: true,
            beforeShow: customRange,
            buttonText: 'Open Calendar',
            firstDay: 1,
            dateFormat: 'D d M yy',
            onSelect: function(date) {
                date = $(this).datepicker('getDate');
                if($(this).attr("id") != 'returningdate'){
                    var returnDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 6);
                    $('#returningdate').val($.datepicker.formatDate('D d M yy', returnDate));
                }
            }
        });
    });

    function customRange(a) {
        var returnDateMin;
        var b = new Date();
        var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
        if (a.id == 'returningdate') 
        {
            if ($('.dDate').datepicker('getDate') != null) {
                c = $('.dDate').datepicker('getDate');
            }
            returnDateMin = new Date(c.getFullYear(), c.getMonth(), c.getDate() + 6);
        }
        else
        {
            returnDateMin = c;
        }
        return {
            minDate: returnDateMin
        }
    }

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

Navigating the parent navController in Ionic 2: A step-by-step guide

I'm currently honing my skills in Ionic 2 by creating a basic app, but I've encountered an issue that has me stumped. The app features an ion-nav element for the login page, then transitions to a tabs navigator after successful login. The struct ...

Exploring an XML document with HTML

I have an XML file that is paired with an XSL file. The resulting output can be located here. I am working on creating an HTML webpage where users can input a search query, such as 'Year < 2009', into a search box. The table above will then d ...

Executing a controller function in AngularJS from an event

I am facing an issue with my AngularJS code. I have defined a function within my controller, and I am trying to call it inside an event listener, but I keep getting an 'undefined' error. Here is how the controller code looks like: inputApp.cont ...

Looking to Identify a Click Within a Complicated Component and Retrieve the Component's ID

Currently, I am working with React for development and have a need to capture clicks at the topmost parent level for performance reasons. const clickHandler = (e) => { console.log("clickHandler", e.target) --> I want to identify the child ...

Utilize JQuery to Extract HTML Elements

I'm working on developing a Chrome extension and one of my tasks is to extract specific text from the webpage I am currently visiting and store it in a variable. I have been attempting to achieve this using jQuery, however, none of the solutions I&apo ...

Showcasing the template dynamically in Angular directive as the scope changes

Provided below is my custom directive: function ajaxMessageData() { var ajaxMessage = { link: link, restrict: "EA", template: "success", scope: { success: '=' } }; return ajaxMessa ...

The functionality of the slick slider seems to be malfunctioning

I've been trying to integrate the slick slider into my website, but it just won't work. I've double-checked everything multiple times, but I can't seem to find the issue. It's driving me crazy! If anyone can help me identify the pr ...

The function "onClick" within an external .js file is being referenced

Just starting to learn Javascript and experimenting with an onClick event for an image in an external .js file using the HTML tag. <script type="text/javascript" src="embed.js"> The code found in "embed.js" is as follows: var image1=new Image(); i ...

What methods can I use to troubleshoot queries being sent through mysql2?

According to the readme for mysql2: MySQL2 is mostly compatible with mysqljs This package includes an option described as: debug: This option prints protocol details to stdout. It can be set to true/false or an array of packet type names that should b ...

What is the best way to incorporate images and videos into a JSON quiz format?

I am working on creating a quiz using JSON, jQuery, and JavaScript. Here is the question I have in JSON format: "questions": [ { "q": "At a birthday party you counted 120 eyes. How many people were at the party?", "a": [ ...

Data in JSON format is not sourced from a text file

My latest project involved creating two new files within a folder titled "hello". These files are named index.html and jsontext.txt. The contents of index.html look like this: <!DOCTYPE html> <html> <head> <title>Experiment< ...

Pictures that can be chosen in a fashion similar to checking off a box

I am just starting out in the world of web development and I have a specific idea in mind. I want to create images that act like checkboxes, where only one can be selected at a time. Here is an example of what I'm looking for: https://i.sstatic.net/Nu ...

Node.js square brackets notation for functions [function] or [function: isBuffer]

Apologies for what may seem like a beginner question. I've been exploring the global variable in node.js and I'm puzzled by the syntax. It appears to be a JSON object, but it's formatted as follows: reallyExit: [Function: reallyExit], bindi ...

Tips on customizing regex to selectively identify specific strings without capturing unrelated ones

Currently, I am working with this regex: /(?<=^|\/)(?:(?!\/)(?!.*\/))(.*?)[:-]v([\d.-]+)(?=\.|$)/ The goal is to extract the captured group from the following strings: rhmtc/openshift-velero-plugin-rhel8:v1.7.9-4 oc-mirror-plug ...

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

Run XQuery dynamically in JavaScript and store the outcome in a JavaScript variable

Looking to achieve the following: Running a dynamic XQUERY stored in a JavaScript variable example var myxquery = For Channels.Channel where Channel/availability = yes And Channels.Channel/Label = 'CNN' Return EXIST(Channels.Channel/Id)&apo ...

Issue with Bootstrap 4 Grid Layout System

Recently delved into the world of Bootstrap 4 and its responsive grid system. Everything seemed to be going smoothly with my columns and resizing windows, until I encountered an issue on xs screensize where all columns automatically spanned 12 instead of ...

Troubles with DropDownList onChange event when selectedIndex is at 0

Hey there, I have a question that's been puzzling me. I have three security question dropdown menus on my ASPX page with JavaScript that removes and repopulates questions based on user selection. Everything works great when editing an existing profile ...

Exploring touch interactions using D3.js and TUIO

I'm currently facing a challenge with implementing multi-touch functionality and the d3.slider in my D3 Map. You can see the current state of my project in this video. With the d3 slider, I can spawn points and navigate around the map using touch even ...

ng-select will solely output the term 'collection'

i am having an issue with a ng-select in my contact form. everything is being received correctly except for the value of the ng-select. Instead of getting the selected option from the ng-select, the system just returns the word "array". Below is the port ...