【问题标题】:How to set/format the date of p:calendar on client side?如何在客户端设置/格式化 p:calendar 的日期?
【发布时间】:2015-01-03 17:23:08
【问题描述】:

首先是目前的情况。我有一个 JSF 页面,其中日期是这样呈现的

<h:outputText value="#{bean[date]}" >
    <f:convertDateTime pattern="#{Const.CALENDAR_PATTERN}"/> 
        // contains a calendar pattern, here dd.MMM yyyy
</h:outputText>

在另一个位置有一个p:calendar输入组件,我喜欢通过在客户端点击一个按钮来设置这个日历的值!

第一次硬编码尝试工作正常:

onclick="document.getElementById('calendar_id_input')
    .setAttribute('value', '21.Jan 2015');"

但是当我使用来自 bean 的日期时,模式当然不匹配:

onclick="document.getElementById('calendar_id_input')
    .setAttribute('value', '#{bean[date]}');"

这已被渲染(如果日历接受此模式,也可以正常工作):

onclick="document.getElementById('calendar_id_input')
    .setAttribute('value', 'Sat Jan 03 18:00:57 CET 2015');"

所以我尝试使用 jQuery-datepicker 格式化程序来格式化日期,然后在日历中设置值,如下所示:

onclick="document.getElementById('calendar_id_input')
    .setAttribute('value', $.datepicker
          .formatDate('#{Const.CALENDAR_PATTERN}', new Date( #{bean[date]} )  ) 
     );"

最后一次尝试的完整渲染结果看起来像这样,但不起作用,即根本没有设置日历的值:

onclick="document.getElementById('calendar_id_input')
   .setAttribute('value', $.datepicker
       .formatDate('dd.MMM yyyy', new Date( Sat Jan 03 18:00:57 CET 2015 )  ) 
    );
 return false;;"

这里出了什么问题,我该如何解决?不幸的是,我对 javascript 和/或 jQuery 不是很熟悉..

提前致谢!


根据 BalusC 的回答,我将代码更改为:

onclick="document.getElementById('calendar_id_input')
.setAttribute('value', $.datepicker
.formatDate('#{Const.CALENDAR_PATTERN}', new Date(#{bean[date].time})));"

现在设置了日历的值,但是无论我尝试哪种模式,结果都很奇怪。例如,使用我喜欢使用的模式dd.MMM yyy,我得到了奇怪的结果03. JanuaryJan 2015 我无法想象这些模式可能存在兼容性冲突,因为 primefaces 是基于 jQuery 构建的,不是吗?


其他问题: 一旦设置了日历的值(例如,通过手动从日期选择器中选择日期),输入组件的值属性会正确更新,但日历仍会显示旧值。

【问题讨论】:

  • 只要想一个名词,就会有jquery插件......
  • @vishalsharma 我已经在 jQuery 中找到了 formatDate 函数,但我没有得到它的工作,如上一部分所述。或者你在谈论其他什么?
  • jsf似乎有问题,'#{bean[date]}',我不知道如何在JSF中格式化值,但你可以查一下文档..

标签: javascript jquery jsf


【解决方案1】:

为了最终结束这个问题,我想与您分享我的解决方案。也许将来对其他人有帮助:

PrimeFaces 组件 p:calendar 在客户端 API 中提供了一个 setDate 函数。所以我现在使用的最终解决方案是这样的

<p:calendar widgetVar="calendar_widget_name" />

<p:commandButton type="button"
    onclick="PF('calendar_widget_name').setDate(new Date(#{bean[date].time}));"
/>

【讨论】:

    【解决方案2】:

    下面的 sn-p 应该可以解决你的问题:

    PF('widgetVariable').setDate(new Date(#{bean.getYourDate().time}));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-09
      • 2015-11-19
      • 1970-01-01
      • 2017-05-21
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多