donutguy640 donutguy640 - 3 months ago 17
jQuery Question

datepicker format: how do I get a different format behind the scenes?

I want the date in the text box to display as

MM-DD-YY (or YYYY, idc)
but for the purposes of MySQL, I need it in
YYYY-MM-DD
.

I have found an identical question here, but I can't get the answer to work on my end. I find the title a little misleading, but the problem as described seems identical to me.

jQuery datepicker altFormat not displayed

The
"altField"
input is because I'm not sure if it's included in the
datepicker
, or if it needed to be added. I can't get it to work either way. The PHP is for my own purposes in debugging, so I can see what is about to be put in the query.

<form onsubmit="return(validateEvent())" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>Date</label>
<input type="text" name="datepicker" id="datepicker">
<br/>
<button type="submit" value="submit" name="submit">Add Event</button>
<input type="text" name="altField" id="altField" hidden>




<script>
$( function() {
$( "#datepicker" ).datepicker({
dateFormat: "mm-dd-yy",
altFormat: "yy-mm-dd",
altField: "#altFormat"
});
});




<?php
if( isset($_POST['submit']) ) {
echo "<script>";
$temp = $_POST["datepicker"];
echo "alert('$temp');";
echo "</script>";
}
?>


Someone please help save my sanity O_o

Answer

You had wrong id's and the hidden field should have type=hidden.

Check this:

$( function() {
  $( "#datepicker" ).datepicker({
    dateFormat: "mm-dd-yy",
    altFormat: "yy-mm-dd",
    altField: "#altField"
  });
  $('#btn1').click(function() {
    console.log("Datepicker value: " + $('#datepicker').val());
    console.log("Datepicker alt value: " + $('#altField').val());
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<form onsubmit="" method="post" action="">
  <label>Date</label>
  <input type="text" name="datepicker" id="datepicker">
  <input type="hidden" name="altField" id="altField">
  <br/>
  <button type="submit" value="submit" name="submit">Add Event</button>
</form>
<br /><br />
<button id="btn1">View Values</button>