OiO.lk Blog jQuery How to get datepicker to show today's date in a new form using php
jQuery

How to get datepicker to show today's date in a new form using php


I’m using PHP 8.2 and datepicker.

I have a form. It has two date fields, which both use the datepicker class. When the page loads, the form is empty (new record). But, the date fields default to 1970-01-01. How can I get these date fields to be either: 1) Today’s date (current date) or, 2) empty?

In the code (below), I use value="<?= isset($start_date) ? $start_date : $today; ?>" so if the form doesn’t pass validation, I re-show the form with the values entered.

Code:

// from new form

<?php
$today = date('m/d/Y');
?>

<div class="row">
    <div class="medium-12 columns">
      <label for="start_date"><strong>Start Date:</strong>
        <input type="text" class="datepicker" name="start_date" id="start_date" value="<?= isset($start_date) ? $start_date : $today; ?>" />
      </label>
    </div>
  </div>

  <div class="row">
    <div class="medium-12 columns">
      <label for="end_date"><strong>End Date:</strong>
      <input type="text" class="datepicker" name="end_date" id="end_date" value="<?= isset($end_date) ? $end_date : $today; ?>" />
      </label>
    </div>
  </div>

....

<script>
  $( function() {
    $( ".datepicker" ).datepicker();
  });
</script>

I tried the following from a thread I saw, but it did not work:

<script>
  $( function() {
    $( ".datepicker" ).datepicker({
      defaultDate: new Date(),
      dateFormat: 'mm/dd/yyyy'
    });
  });
</script>

// and 

<script>
  $( function() {
    let date = new Date().toLocaleDateString("en", {year:"numeric", day:"2-digit", month:"2-digit"});

    $( ".datepicker" ).datepicker({ defaultDate: date });

  });
</script>

Thanks for any help.

Cheers!



You need to sign in to view this answers

Exit mobile version