Set a minimum date in a date field in dependence of another date field

Support Meta Box AIO Set a minimum date in a date field in dependence of another date fieldResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #17339
    DanielDaniel
    Participant

    Hey there, I´m new to Meta Box and am trying to get my first results. What I want to achieve is to have two date fields like in a booking engine with a check-in and a check-out date.

    I added two date fields to a group ("from" and "to"). Then I used the dateFormat option to get the right date format for my region. Additionally I added the "save_format" attribute to save the date format for sorting operations.

    Next I tried to format the "to" date in dependence of the from date field. Therefore I used the "minDate" option from the date picker options and hoped that I could get and set the date from the "from" field as a new date in the value field. Finally what I want to achieve is that the "to" field is always after the "from" field. Earlier dates shouldn´t be selectable. Is that achievable?

    Thanks a lot in advance for your help. I really appreciate it.

    Daniel

    #17417
    Anh TranAnh Tran
    Keymaster

    Hi Daniel,

    I tried to format the “to” date in dependence of the from date field. Therefore I used the “minDate” option from the date picker options and hoped that I could get and set the date from the “from” field as a new date in the value field.

    I think this can be done only with custom JavaScript.

    Here are some steps that I'm thinking:

    First, add the following code to functions.php file, this code enqueues a custom JS file:

    add_action( 'rwmb_enqueue_scripts', function() {
        wp_enqueue_script( 'custom-code', get_template_directory_uri() . '/custom.js', ['jquery'], '', true );
    } );

    Second, create a file custom.js and put it in your theme. And put the following code in that file:

    $from = $( '#from' );
    $to = $( '#to' );
    $from.on( 'change', function() {
        $to.datepicker( "option", "minDate", $from.val() );
    } );

    Here I assume your fields has ID from and to. You might want to change it to something else if you have different IDs.

    #17438
    DanielDaniel
    Participant

    Hey Anh,

    I could make it work with your help. I just changed the way to enqueue the script via admin_enqueue_scripts as I wanted to use the datepicker in the backend.

    Thanks a lot and have a nice weekend

    Daniel

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.