Linked datepicker with Jquery

Asked

Viewed 40 times

0

I have a form with a date period ('Start Date' and 'End Date'). The start date may not be less than the end date and the end date may not be less than the start date. These inputs are using the Jquery UI datepicker (Jqueryui 1.11.0 and Jquery 3.1.1).

I searched the Jquery UI documentation and found the example below:

$(function () {
    var dateFormat = "dd/mm/yy",
        from = $("#from")
        .datepicker()
        .on("change", function () {
            to.datepicker("option", "minDate", getDate(this));
        }),
        to = $("#to").datepicker()
        .on("change", function () {
            from.datepicker("option", "maxDate", getDate(this));
        });

    function getDate(element) {
        var date;
        try {
            date = $.datepicker.parseDate(dateFormat, element.value);
        } catch (error) {
            date = null;
        }

        return date;
    }
});

Is there any other way to do it?

1 answer

1


There are many other ways to do this, for example:

using html and jQuery

$( document ).ready(function() {
  $("#dtaInicio, #dtaFinal").change(function(){
   var inicio = document.getElementById("dtaInicio").value;    var fim = document.getElementById("dtaFinal").value;
    console.log(inicio);
    console.log(fim);
   if (new Date(inicio) > new Date(fim)) {
     alert("inicio maior que fim return false");  
     return false;
   }
  
   
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<label>
Data Inicial:
<input id="dtaInicio" type="date" value="" size=10 />
</label>
<label>
Data Final:
<input id="dtaFinal" type="date" value="" size=10 />
</label>

</html>

Try to put an initial date higher than the final, will return false, in the example I put this check in the change of inputs, Voce can put to the Submit of a form

Browser other questions tagged

You are not signed in. Login or sign up in order to post.