Get datepicker defaultdate from string/django object

 ̄綄美尐妖づ 提交于 2019-12-11 00:47:56

问题


I am a total (like no-experience-whatsoever) noob in jquery and Javascript, and what I would like to do is the following:

I pass an article-object to my template that has date-information stored in it. I can access and display that information with {{ article.pubdate }}. Is it possible to set the defaultDate option of datepicker to the article date?
How would I go about that?

Thanks for any pointers!

Update: Some more information about {{ article.pubdate }}:
It is a datetime object. The display format of the string can be edited, so {{ article.pubdate|date:"Y-m-d"}} gives a date like 2013-07-27.

Update 2: I display the article date on the page like this:

<div id="article-pubdate">
        {{ article.pubdate|date:"Y-m-d" }}
</div>

This gives me 2013-07-27 as a string displayed on the page. After reading around I tried the following approach to get that string into datepicker like so:

<script>
  $(function () {
      var a = $("#article-pubdate").text();
      var the_date = $.datepicker.parseDate("yy-mm-dd", a);
      $(".datepicker input").datepicker({
          dateFormat: "yy-mm-dd",
          changeMonth: true,
          changeYear: true,
          yearRange: '1990:2013',
          defaultDate: the_date,
      });
  });
</script>

But this doesn't work, why?

Update 2: If I set defaultDate like so:

<script>
  $(function() {
    $( ".datepicker input" ).datepicker({
         dateFormat: "yy-mm-dd",
         changeMonth: true,
         changeYear: true,
         yearRange:'1990:2013',
         defaultDate:"2001-01-01"
    });
  });
</script>

it works absolutely fine. Is there any way to pass the date info directly into datepicker?


回答1:


You can set default date using setDate

You need to use this after initialization of datepicker, for that you need to pass date Object

$('#datepicker').datepicker(datepicker({
      dateFormat: "yy-mm-dd",
      changeMonth: true,
      changeYear: true,
      yearRange: '1990:2013',
  });

$('#datepicker').datepicker('setDate', new Date($("#article-pubdate").text().replace(/\-/g, ',')));


来源:https://stackoverflow.com/questions/17897835/get-datepicker-defaultdate-from-string-django-object

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