samedi 3 janvier 2015

How to set/format a date using JavaScript and/or jQuery?

First of all the current situation. I have a JSF page where a date is rendered like this



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


On another location there is a p:calendar input component, and I like to set the value of this calendar via a button click on the client side!


A first hard coded attempt works fine:



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


But when I am using the date, that comes from the bean, then the pattern does not match, of course:



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


This got rendered to (and would work fine as well, if the calendar would accept this pattern):



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


So I tried using the jQuery-datepicker formatter to format the the date before I set the value in the calendar like this:



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


The full rendered outcome in the last attempt looks like this, but does not work, ie the value of the calendar is not set at all:



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;;"


What is wrong here and how may I fix it? Unfortunately I am not very familar with javascript and/or jQuery..


Thanks in advance!


Aucun commentaire:

Enregistrer un commentaire