phphtmlformsdatepicker

How to retain the selected dates in datepicker after submit in PHP


I have 2 datepickers From and To, one submit button in PHP. When selected the dates in two datepickers and click the submit button, the datepicker's values return to default. Here is the code I used.

<div class="col-md-8">
            <form autocomplete="off" class="form-inline" method="POST" action="">
                <?php
                    $firstday = date('Y-m-01');
                    $lastday = date('Y-m-t');
                ?>
                <label>Date:</label>
                <input type="date" id="myDate1" name="date1" value="<?php echo $firstday;?>">
                <label>To</label>
                <input type="date" id="myDate2" name="date2" value="<?php echo $lastday;?>">
                <button class="btn btn-primary" name="search"><span class="glyphicon glyphicon-search"></span></button>
</form>

enter image description here

What i need is to retain the selected values after submit. Thank you!


Solution

  • You can check and see if the date was posted and if it was use that date instead of the default. Check the $_POST variable for the value

            <form autocomplete="off" class="form-inline" method="POST" action="">
                <?php
                    if (isset($_POST['date1'] && isset($_POST['date2']){
                      $firstday = $_POST['date1']; 
                      $lastday = $_POST['date2']; 
                    }
                    else{
                      $firstday = date('Y-m-01');
                      $lastday = date('Y-m-t');
                    }
                ?>
                <label>Date:</label>
                <input type="date" id="myDate1" name="date1" value="<?php echo $firstday;?>">
                <label>To</label>
                <input type="date" id="myDate2" name="date2" value="<?php echo $lastday;?>">
                <button class="btn btn-primary" name="search"><span class="glyphicon glyphicon-search"></span></button>