Search code examples
jqueryhtmldatepickermaterialize

Datepicker with different rules


I am using materialize.min.js then trouble happens when using different rules about min and max for each datepicker in a form.

The below code is not working. Any idea?

<script>    
    $(document).ready(function() {
        $('select').material_select();
        $('.datepicker').pickadate({
          firstDay: 1,
          selectYears: true,
          selectMonths: true,
          onSet: function(object) {
            if (object.select) {
              this.close();
            }
          }
        });
        $('#dt1').pickadate({
          min: new Date(new Date().getFullYear()-75,1,1),
          max: new Date(new Date().getFullYear()-18,12,31)
        });
        $('#dt2').pickadate({
          min: new Date(new Date().getFullYear()-14,new Date().getMonth(), new Date().getDate()),
          max: new Date(new Date().getFullYear(),new Date().getMonth(), new Date().getDate())
        });
    });
</script>

Solution

  • Have you tried something like this?

    $(document).ready(function() {
        $('select').material_select();
        $('#dt1').pickadate({
          min: new Date(new Date().getFullYear()-75,1,1),
          max: new Date(new Date().getFullYear()-18,12,31),
          firstDay: 1,
          selectYears: true,
          selectMonths: true,
          onSet: function(object) {
            if (object.select) {
              this.close();
            }
          }
        });
        $('#dt2').pickadate({
          min: new Date(new Date().getFullYear()-14,new Date().getMonth(), new Date().getDate()),
          max: new Date(new Date().getFullYear(),new Date().getMonth(), new Date().getDate()),
          firstDay: 1,
          selectYears: true,
          selectMonths: true,
          onSet: function(object) {
            if (object.select) {
              this.close();
            }
          }
        });
    });
    

    I assume, that the second call of pickadate might not update the ranges correctly after the first initialisation.

    EDIT:

    To reduce loc you could extend a basic set of options into two objects and assign them later

    var baseOptions = {
      firstDay: 1,
      selectYears: true,
      selectMonths: true,
      onSet: function(object) {
        if (object.select) {
          this.close();
        }
      }
    }
    $('#dt1').pickadate(Object.assign(baseOptions, {
      min: new Date(new Date().getFullYear()-75,1,1),
      max: new Date(new Date().getFullYear()-18,12,31)
    })