Why does building a jQuery UI Datepicker clear a field value?

I have an INPUT tag with the value attribute set to "15-May-2012" and I initialized the JQuery UI Datepicker as follows:

<input type="text" name="schedule" id="schedule" value="15-May-2012"> <script type="text/javascript"> $(function() { $( "#schedule" ).datepicker(); $( "#schedule" ).datepicker( "option", "dateFormat", "dM-yy" ); }); </script> 

For some reason, the value of the INPUT tag is cleared after the Datepicker is initialized. Note that the value in the INPUT field matches the format set for Datepicker.

Why is the meaning cleared?

Here is a live example: http://agnelkurian.com/lab/datepicker_example.html

+4
source share
3 answers

When binding datepicker:

 $('#schedule').datepicker(); 

it will use the default dateFormat and this is "mm/dd/yy" ; your "15-May-2012" does not conform to this format, so the datepicker clears it when it cannot parse it using "mm/dd/yy" . Then you change the format:

 $("#schedule").datepicker("option", "dateFormat", "dM-yy"); 

but value already lost.

You must set the format when you bind datepicker:

 $("#schedule").datepicker({ dateFormat: 'dM-yy' }); 

Demo: http://jsfiddle.net/ambiguous/mHyn7/

+12
source

A simple solution that really works:

 var tmp = $('#schedule').val(); $("#schedule").datepicker("option", "dateFormat", "dM-yy"); $("#schedule").val(tmp); 
+2
source
  $( "#schedule" ).datepicker(); $( "#schedule" ).datepicker( "option", "dateFormat", 'dM-yy' ); $( "#schedule" ).val("15-May-2012"); 
-1
source

Source: https://habr.com/ru/post/1410945/


All Articles