Disable selection jQuery Datepicker field?

2019-08-05 09:36发布

问题:

I'm using jQuery UI Datepicker to make a two field submission form. I want the user to create a range and submit it to see results. However, they obviously cannot pick a start date that happens more recently than an end date (you can't see a range starting today and going to yesterday). As of now, I've been able to put an alert on selection of the second one if the first one happened before it, but I can't figure out how to have the datepicker stay open so the user can select something else.

Here is the code I have so far:

<script>
    $(document).ready(function() {
        $(".datepicker_start").datepicker({
            maxDate: '+0d',
            onSelect: function(dateText, inst) {

        }
        });
        $(".datepicker_to").datepicker({
            maxDate: '+0d',
            onSelect: function(dateText, inst) {
                 var startDate = $('.datepicker_start').val();
                $(this).attr('value', dateText)
                if (startDate > dateText) {
                    alert('not cool!');
                }
        }
        });
    });
</script>

Does anyone know how I'd do this? I tried returning false but it still pushes the incorrect date to the field :(

回答1:

$(function() {
    $( "#from" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function( selectedDate ) {
            $( "#to" ).datepicker( "option", "minDate", selectedDate );
        }
    });
    $( "#to" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function( selectedDate ) {
            $( "#from" ).datepicker( "option", "maxDate", selectedDate);
        }
    });
});

From: http://jqueryui.com/demos/datepicker/date-range.html



回答2:

  $(function () {
        $("#fromdate").datepicker({
            onClose: function (selectedDate) {
                $("#todate").datepicker("option", "minDate", selectedDate);
            }
        });
        $("#todate").datepicker({
            onClose: function (selectedDate) {
                $("#fromdate").datepicker("option", "maxDate", selectedDate);
            }
        });
    });