Set date input field's max date to today

前端 未结 10 593
说谎
说谎 2020-12-02 19:37

I just have a simple line of code like this:


Is there a sim

相关标签:
10条回答
  • 2020-12-02 20:14

    Javascript will be required; for example:

    $(function(){
        $('[type="date"]').prop('max', function(){
            return new Date().toJSON().split('T')[0];
        });
    });
    

    JSFiddle demo

    0 讨论(0)
  • 2020-12-02 20:15

    Yes, and no. There are min and max attributes in HTML 5, but

    The max attribute will not work for dates and time in Internet Explorer 10+ or Firefox, since IE 10+ and Firefox does not support these input types.

    EDIT: Firefox now does support it

    So if you are confused by the documentation of that attributes, yet it doesn't work, that's why.
    See the W3 page for the versions.

    I find it easiest to use Javascript, s the other answers say, since you can just use a pre-made module. Also, many Javascript date picker libraries have a min/max setting and have that nice calendar look.

    0 讨论(0)
  • 2020-12-02 20:23

    I also had same issue .I build it trough this way.I used struts 2 framework.

      <script type="text/javascript">
    
      $(document).ready(function () {
      var year = (new Date).getFullYear();
      $( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate: 
      0});
    
      });
    
    
      </script>
    
            <s:textfield name="effectiveDate" cssClass="input-large" 
       key="label.warrantRateMappingToPropertyTypeForm.effectiveDate" 
       id="effectiveDateId" required="true"/>
    

    This worked for me.

    0 讨论(0)
  • 2020-12-02 20:24

    A short but may be less readable version of one of the previous answers.

       <script type="text/javascript">
        $(document).ready(DOM_Load);
    
        function DOM_Load (e) {
            $("#datefield").on("click", dateOfBirth_Click);
        }
    
        function dateOfBirth_Click(e) {
            let today = new Date();
            $("#datefield").prop("max", `${today.getUTCFullYear()}-${(today.getUTCMonth() + 1).toString().padStart(2, "0")}-${today.getUTCDate().toString().padStart(2, "0")}`);
        }
    
    </script>
    
    0 讨论(0)
  • 2020-12-02 20:25

    JavaScript only simple solution

    datePickerId.max = new Date().toISOString().split("T")[0];
    <input type="date" id="datePickerId" />

    0 讨论(0)
  • 2020-12-02 20:27

    In lieu of Javascript, a shorter PHP-based solution could be:

     <input type="date" name="date1" max=
         <?php
             echo date('Y-m-d');
         ?>
     >
    
    0 讨论(0)
提交回复
热议问题