jQuery: Datepicker # Dates Selected

Hi, trying to calculate the days between the two datepickers on this page.

What I have so far in JS:

$("#booking_calender").datepicker({
	    minDate: 0,
	    maxDate: '+1Y+6M',
	    onSelect: function (dateStr) {
	        var min = $(this).datepicker('getDate'); // Get selected date
	        $("#booking_calender_checkout").datepicker('option', 'minDate', min || '0'); // Set other min, default to tod
	    }
	});

	$("#booking_calender_checkout").datepicker({
	    minDate: '0',
	    maxDate: '+1Y+6M',
	    onSelect: function (dateStr) {
	        var max = $(this).datepicker('getDate'); // Get selected date
	        $('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to +18 months
	        var start = $("#booking_calender").datepicker("getDate");
	        var end = $("#booking_calender_checkout").datepicker("getDate");
	        var days = (end - start) / (1000 * 60 * 60 * 24);
	        $( '.caption.product-calc-days span.numDays' ).append( document.createTextNode( days ) );
	    }
	});

The html:
Datepicker 1:

<input type="text" id="booking_calender" name="booking_calender" class="booking_calender hasDatepicker" style="cursor: text!important;" readonly="" placeholder="Delivery">

Datepicker 2:

<input type="text" id="booking_calender_checkout" name="booking_calender_checkout" class="booking_calender hasDatepicker" style="cursor: text!important;" readonly="" placeholder="Drop Off">

html where the # of days should post (.numDays):

<div class="caption product-calc-days">Total Rental Days: <span class="numDays"></span></div>

I feel like I am almost there! Appreciate any help :slight_smile:
Luke

  • Ash

    Hello Luke

    Your code worked perfectly fine for me, please check the following screenshot.

    So, double check where you inserted the code if there is anything missing or posted in right place.

    One thing I want to add, in the following line:

    $( '.caption.product-calc-days span.numDays' ).append( document.createTextNode( days ) );

    replace append with html method. As, if the user selects another date, then the new difference of the dates are appended with the previous one.

    So better use:

    $( '.caption.product-calc-days span.numDays' ).html( document.createTextNode( days ) );

    Hope it helps! Please feel free to ask more questions if you have any.

    Have a nice day!

    Cheers,
    Ash

  • Luke

    Thank you very much for looking into this for us Ash.

    I added the code to our custom-js.js file that runs on every page of the site. But when we include the full code shown in your screenshot, the end date switches the month and day and the totals below are configured incorrectly. You can even see it in your screenshot that the day and month's switch. Quite strange.

    Here is the exact code we added to custom-js.js:

    $("#booking_calender_checkout").datepicker("destroy");
    
      $("#booking_calender_checkout").datepicker({
          minDate: '0',
          maxDate: '+1Y+6M',
          onSelect: function (dateStr) {
              var max = $(this).datepicker('getDate'); // Get selected date
              $('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to +18 months
              var start = $("#booking_calender").datepicker("getDate");
              var end = $("#booking_calender_checkout").datepicker("getDate");
              var days = (end - start) / (1000 * 60 * 60 * 24);
              $( '.caption.product-calc-days span.numDays' ).html( document.createTextNode( days ) );
          }
      });

    I was curious what this line was for?

    $("#booking_calender_checkout").datepicker("destroy");

    Let me know if you need access to our ftp. Thanks again for having a look at this for us :slight_smile:
    Luke

  • Luke

    on this note. . .
    In order for the date to display we need to translate the datepicker dateformat to mm/dd/yy

    this code works great, but it needs to display properly (mm/dd/yy) or other elements will not work.
    Current display is in mm/dd/yyyy.

    we are looking to lose the "20" on "2017"

    And the code:

    (function($) { // mandantory for Wordpress
    $(document).ready(function() {
    	$("#booking_calender_checkout").datepicker("destroy");
    	$("#booking_calender_checkout").datepicker({
    	    minDate: '0',
    	    maxDate: '+1Y+6M',
    	    onSelect: function (dateStr) {
    	        var max = $(this).datepicker('getDate'); // Get selected date
    	        // $('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to +18 months
    	        $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }, 'option', 'maxDate', max || '+1Y+6M');
    	        var start = $("#booking_calender").datepicker("getDate");
    	        var end = $("#booking_calender_checkout").datepicker("getDate");
    	        // var days = (end - start) / (1000 * 60 * 60 * 24);
    	        var days = Math.round( (end - start) / (1000 * 60 * 60 * 24));
    	        var days1 = days + 1;
    	        $( '.caption.product-calc-days span.numDays' ).html( document.createTextNode( days ) );
    	        //getter
    			var dateFormat = $( "input#booking_calender_checkout" ).datepicker( "option", "dateFormat" );
    			//setter
    			$( "input#booking_calender_checkout" ).datepicker( "option", "dateFormat", 'mm/dd/yy' );
    	    }
    	});
    });
    })( jQuery ); // mandantory for Wordpress

    I have determined, with the help of Patrick :grinning: the problem arises on this line:

    $( "input#booking_calender_checkout" ).datepicker( "option", "dateFormat", 'mm/dd/yy' );

    If you have any idea how to display the date properly from this snippet, we greatly appreciate it :slight_smile:
    Thanks again,
    Luke

  • Luke

    We've had a lot of trouble with this little datepicker value between dates issue.

    First off, Ash found a solution with this code:

    $(function($){
    	$('#booking_calender_checkout').datepicker('destroy');
    
    	$('booking_calender_checkout').datepicker({
    		minDate: '0',
    		maxDate: '+1Y+6M',
    		onSelect: function (dateStr) {
    			var max = $(this).datepicker('getDate');
    			$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M');
    			var start = $('#booking_calender').datepicker('getDate');
    			var end = $('#booking_calender_checkout').datepicker('getDate');
    			var days = (end - start) / (1000 * 60 * 60 * 24);
    			$('.caption.product-calc-days span.numDays').append(document.createTextNode(days));
    		}
    	});
    });

    After a little alteration we came to this code as a solution, but it only worked for about 12-14 hours. lol

    $(document).ready(function() {
    	$("#booking_calender_checkout").datepicker("destroy");
    	$("#booking_calender_checkout").datepicker({
    	    minDate: '0',
    	    maxDate: '+1Y+6M',
    	    onSelect: function (dateStr) {
    	        var max = $(this).datepicker('getDate'); // Get selected date
    	        // $('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to +18 months
    	        $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }, 'option', 'maxDate', max || '+1Y+6M');
    	        var start = $("#booking_calender").datepicker("getDate");
    	        var end = $("#booking_calender_checkout").datepicker("getDate");
    	        // var days = (end - start) / (1000 * 60 * 60 * 24);
    	        var days = Math.round( (end - start) / (1000 * 60 * 60 * 24));
    	        var days1 = days + 1;
    	        $( '.caption.product-calc-days span.numDays' ).html( document.createTextNode( days ) );
    	        //getter
    			var dateFormat = $( "input#booking_calender_checkout" ).datepicker( "option", "dateFormat" );
    			//setter
    			$( "input#booking_calender_checkout" ).datepicker( "option", "dateFormat", 'dd/mm/yy' );
    	    }
    	});
    });

    Somehow it made the end date datepicker have a (yyyy) year, contrary to the (mm/dd/yy) date we originally had. It also at times made the end date datepicker un-clickable.

    Check out the page we have been running it on in the console.

    If you need any more info, please let me know. Thanks!

    p.s. I want to give my kudos to Majid & Ash for sticking with me through the muck and the mire :slight_smile: its been real.

    Luke

  • Ash

    Hello Luke

    First of all, you should not use this line in this case:

    $('#booking_calender_checkout').datepicker('destroy');

    This line I used to terminate the current datepicker and then I run another one. As I was running little modified code in console, and already your datepicker function was working on that input field, so I had to terminate the current one.

    I have written some code creating almost same scenario of yours, you may take a look and make required modification: http://jsbin.com/mubunigihi/1/edit?html,js,output

    Hope it helps! Please feel free to ask more questions if you have any.

    Have a nice day!

    Cheers,
    Ash

  • Luke

    Thanks for getting back to us on this Ash. I went ahead and tested with the new code you provided (changed out the datepicker id's, loaded in the console, etc.). Although I was unable to run the code successfully, I can show you exactly what changes I made, and hopefully, you see where the issue lies.

    functions.php, where the js file is enqueued (on every update of the js file I change the version #):

    function my_theme_scripts() {
        if (is_page('cart')) {
        wp_enqueue_script( 'test', get_stylesheet_directory_uri() . '/js/cart-js.js', array( 'jquery' ), '5.0.1', false );
        }
        if (is_product()) {
            wp_enqueue_script( 'test', get_stylesheet_directory_uri() . '/js/product-js.js', array( 'jquery' ), '5.0.9', true);
        }
    }
    add_action( 'wp_enqueue_scripts', 'my_theme_scripts', 99 );

    The js file contents:

    (function($) { // mandantory for Wordpress
    
    /////////////////// Second Code snippet from Ash
    
    $(function($){
    
      $("#booking_calender").datepicker({
    	    minDate: 0,
            dateFormat: 'mm/dd/y',
    	    maxDate: '+1Y+6M',
    	    onSelect: function (dateStr) {
    	        var min = $(this).datepicker('getDate'); // Get selected date
    	        $("#booking_calender_checkout").datepicker('option', 'minDate', min || '0'); // Set other min, default to tod
    	    }
    	});
    
      $("#booking_calender_checkout").datepicker({
    	    minDate: '0',
            dateFormat: 'mm/dd/y',
    	    maxDate: '+1Y+6M',
    	    onSelect: function (dateStr) {
    	        var max = $(this).datepicker('getDate'); // Get selected date
    	        var start = $("#booking_calender").datepicker("getDate");
    	        var end = $("#booking_calender_checkout").datepicker("getDate");
    	        var days = (end - start) / (1000 * 60 * 60 * 24);
    	        $( 'span.numDays' ).val( parseInt( days ) );
    	    }
    	});
    });
    
    /////////////////// Second Code snippet from Ash END
    
    })( jQuery ); // mandantory for Wordpress

    Start Date HTML:

    <div class="bkap_start_date">
    <label class="book_start_date_label" style="margin-top:1em;">Select Rental Dates: </label>
    <input type="text" id="booking_calender" name="booking_calender" class="booking_calender hasDatepicker" style="cursor: text!important;" readonly="" placeholder="Delivery"><img src="//localhost:3000/wp-content/plugins/woocommerce-booking/images/calendar1.gif" width="20" height="20" style="cursor:pointer!important;" id="checkin_cal"><div id="inline_calendar"></div>
    </div>

    End date HTML:

    <div class="bkap_end_date">
    <label class="book_end_date_label">to: </label>
    <input type="text" id="booking_calender_checkout" name="booking_calender_checkout" class="booking_calender hasDatepicker" style="cursor: text!important;" readonly="" placeholder="Drop Off"><img src="//localhost:3000/wp-content/plugins/woocommerce-booking/images/calendar1.gif" width="20" height="20" style="cursor:pointer!important;" id="checkout_cal"><div id="inline_calendar_checkout"></div>
    </div>

    The HTML where the #of days should show (class numDays):

    <div class="caption product-calc-days">Total Rental Days: <span class="numDays"></span></div>

    In terms of placing the calculated # of days (var days), because it is simply a span with an ID, I tried to append the variable in this manner:

    $( days ).appendTo( '.caption.product-calc-days span.numDays' );

    . . . but I am not sure if your original .val solution would work just as good.

    $( 'span.numDays' ).val( parseInt( days ) );

    Always appreciate your help. I feel like we're super close :slight_smile: Thanks again for your support.
    Luke

  • Ivan

    Hi Luke !

    First of all, you can use time() function as version # for js files while you develop :slight_smile: For example wp_enqueue_script( 'test', get_stylesheet_directory_uri() . '/js/cart-js.js', array( 'jquery' ), time(), false );

    if your original .val solution would work just as good

    I don't see where Ash recommend it. Yes, it won't work for span tags. You can use it in thi place
    $( 'span.numDays' ).text( parseInt( days ) );
    If it won't help - provide me with additional login credentials, I can look into it more.

    https://premium.wpmudev.org/contact/#i-have-a-different-question
    Please visit our private Contact page and complete the form with the following information:

    Subject: "Attn: Ivan Svyrskyi"

    In the Message box, please provide the following:

    - link back to this thread for reference
    - describe what do you want to reach with this js code with more detail and screenshots
    - any other relevant urls

    - Admin login:
    Admin username
    Admin password
    Login url

    - FTP/SFTP credentials
    host
    username
    password
    (and port if required)

    Note: Don't send any credentials via this forum because it's public forum.

    Best regards,
    Ivan.

  • Luke

    Hi, Ivan,

    The rental dates are including start and end date. So in this example, the Total Rental Days should be 11:

    I changed your code in the product-js.js file to " + 2" but the changes are not showing:

    It looks like everything is working though! Really appreciate you looking at it for us.

    One interesting thing I found is that the calendar days are reconfigured or moved:

    Let me know if that answers your question, or if you have any more questions.

    Thanks again,
    Luke

  • Ivan

    Hi Luke !

    It happened because you change rentDays and then don't use it. I changed last lines like

    var rentDays = days + 1;
    $( 'span.numDays' ).text( parseInt( rentDays ) );

    and it works as you want.
    Regarding

    One interesting thing I found is that the calendar days are reconfigured or moved

    First screenshot: it hides from 3.10 to 10.10 because it set on settings of this product ( {your_domain}/wp-admin/post.php?post=1363&action=edit booking section -> availability -> Advance Booking Period (in hours) )
    Second screenshot: after selecting 16.10 at first datepicker it hides 16.10 and 17.10 because it also set on this page ( booking section -> availability -> Minimum number of nights to book )

    Let me know if I missed something.
    Best regards,
    Ivan.

  • Luke

    Hi, Ivan, I totally overlooked the dates you mentioned. My apologies.

    Although the calendar week start date changing is strange, don't you think? It went from the week start date on Sunday to Monday.

    The script totally works for the Total Rental Days (thank you for that :slight_smile:, but unfortunately it messes with the ajax on date selection. In order for the bottom totals to display correctly, you have to re-select the start date after you have set both the start date and end date.

    Let me know if you are seeing this as well on our rental product. Thanks again for your expertise.
    -Luke

  • Ivan

    Hi Luke !

    It seems the page on your site which you shared doesn't work now. If you provide me with additional login credentials, I can look into it more.

    https://premium.wpmudev.org/contact/#i-have-a-different-question
    Please visit our private Contact page and complete the form with the following information:

    Subject: "Attn: Ivan Svyrskyi"

    In the Message box, please provide the following:

    - link back to this thread for reference
    - work link with datepickers;
    - any other relevant urls

    - Admin login:
    Admin username
    Admin password
    Login url

    - FTP/SFTP credentials
    host
    username
    password
    (and port if required)

    Note: Don't send any credentials via this forum because it's public forum.

    Best regards,
    Ivan.

  • Ivan

    Hi Luke !

    It seems grant access to your site was expired.
    If you provide me with additional login credentials for your new site, I can look into it more.

    https://premium.wpmudev.org/contact/#i-have-a-different-question
    Please visit our private Contact page and complete the form with the following information:

    Subject: "Attn: Ivan Svyrskyi"

    In the Message box, please provide the following:

    - link back to this thread for reference
    - work link with datepickers;
    - any other relevant urls

    - Admin login:
    Admin username
    Admin password
    Login url

    - FTP/SFTP credentials
    host
    username
    password
    (and port if required)

    Note: Don't send any credentials via this forum because it's public forum.

  • Ivan

    Hi Luke !

    You should add span with numDays class again where you want to see the difference. And use the following JS-code (I already added it to the product-js.js file on your site)

    $(document).ready(function($) {
       	$('body').on('bkap_price_updated', function() {
            var diff = $("#wapbk_diff_days").val();
    		if ( typeof diff !== 'undefined' && diff !== 'NaN' ) {
    			$( 'span.numDays' ).text( parseInt( diff ) );
    		}
    	});
    });

    Best regards,
    Ivan.

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.