Why does constructing a JQuery UI Datepicker clear the field's value?

江枫思渺然 提交于 2020-01-03 17:22:55

问题


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

<input type="text" name="schedule" id="schedule"
      value="15-May-2012">

<script type="text/javascript">
  $(function() {
    $( "#schedule" ).datepicker();
    $( "#schedule" ).datepicker( "option", "dateFormat", "d-M-yy" );
  });
</script>

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

Why is the value cleared?

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


回答1:


When you bind the datepicker:

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

it will use the default dateFormat and that is "mm/dd/yy"; your "15-May-2012" doesn't match that format so the datepicker clears it when it fails to parse it using "mm/dd/yy". Then you change the format:

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

but the value has already been lost.

You should set the format when you bind the datepicker:

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

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




回答2:


Simple solution that actually works:

var tmp = $('#schedule').val();
$("#schedule").datepicker("option", "dateFormat", "d-M-yy");
$("#schedule").val(tmp);



回答3:


    $( "#schedule" ).datepicker();
$( "#schedule" ).datepicker( "option", "dateFormat", 'd-M-yy' );
$( "#schedule" ).val("15-May-2012");


来源:https://stackoverflow.com/questions/10468547/why-does-constructing-a-jquery-ui-datepicker-clear-the-fields-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!