Foros de discusión

DatePicker rendering on a specific input field

Low Trux, modificado hace 9 años.

DatePicker rendering on a specific input field

Junior Member Mensajes: 64 Fecha de incorporación: 6/11/14 Mensajes recientes
I have an Alloy UI Datepicker calendar and what i was trying to do is to trigger the calendar with an icon but display the dates on an input field, i have been trying to use render but it still dont work, this is my code:

<aui:script>
YUI( { lang: 'ca-ES' } ).use(
		  'aui-datepicker',
  	 
	  function(Y) {
			 
		  var datepickerAlta = new Y.DatePicker(
		      {
		        trigger: '.icon-calendar',
		        mask: '%d/%m/%Y',
		        popover: {
		        	toolbars: {
			            header: [[
			              {
			                icon:'icon-trash',
			                label: 'Limpiar',
			                on: {
			                  click: function() {
			                    datepickerAlta.clearSelection();
			                  }
			                }
			              }
			            ]]
			          },
          
	            	zIndex: 1	
	            },
	            after: {
	            		selectionChange: function(event) {
							fillTable('&lt;%=sessionBean.getEns().getIdEns() %&gt;');
			         	}
			      	}
		      }
     	  );
		  
		  var datepickerFins = new Y.DatePicker(
			      {
			        trigger: '.icon-calendar',
			        mask: '%d/%m/%Y',
		        	popover: {
			        	toolbars: {
				            header: [[
				              {
				                icon:'icon-trash',
				                label: 'Limpiar',
				                on: {
				                  click: function() {
				                    datepickerFins.clearSelection();
				                  }
				                }
				              }
				            ]]
				          },		        	
						zIndex: 1	
		            },
		            after: {
		            		selectionChange: function(event) {
								fillTable('&lt;%=sessionBean.getEns().getIdEns() %&gt;');
				         	}
				      	}
			      }
     	  ); 
     	  
	}
);

</aui:script>


And this is the html:

<div class="input_alta input_datepicker">
<label><liferay-ui:message key="dataAlta" /></label>
<i class="icon-calendar icon-1x"></i>
<input id="startDate" placeholder="dd/mm/aaaa" value="" type="text">
</div>


<div class="input_fins input_datepicker">
<label><liferay-ui:message key="fins" /></label>
<i class="icon-calendar icon-1x"></i>
<input id="endDate" placeholder="dd/mm/aaaa" value="" type="text">
</div>


The icons have to trigger the calendar (there two calendars so there's also two icons and two inputs) but the dates have to be shown in the input, any help will be really appreciated.
thumbnail
Kyle Joseph Stiemann, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Liferay Master Mensajes: 760 Fecha de incorporación: 14/01/13 Mensajes recientes
Hi Low Trux,
Your code has a couple issues:
  • trigger: '.icon-calendar', will attach the DatePicker to any element with CSS class .icon-calendar. This means that both DatePickers will be attached to both icons, which I don't believe is the behavior you want. You should probably specify a different id for both icons and attach the trigger to the id directly, like so: trigger: '#iconId1',.
  • Depending on which version of Liferay or AlloyUI you are using, you may be affected by AUI-1205, a bug in the selectionChange event. If you are affected by AUI-1205, you can work around it by using the internal Calendar object's dateClick event.
  • You are missing any code that would update the inputs. You need to do something like A.one('#startDate').set('value', A.Date.format(event.date,{format:datePicker.get('mask')})); in your selectionChange/dateClick event function.

I've answered almost the exact same question on StackOverflow, so you can check out that answer for a detailed code example and explanation.

- Kyle
thumbnail
Kyle Joseph Stiemann, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Liferay Master Mensajes: 760 Fecha de incorporación: 14/01/13 Mensajes recientes
Alternatively, an even simpler way to do this (which may or may not fit your use case) is to set the input as the trigger of the DatePicker, but have the icon show the DatePicker on click:

<i id="icon" class="icon-calendar icon-1x"></i>
<input id="date" type="text" />
<script>
YUI().use('aui-datepicker', function (Y) {

var datePicker = new Y.DatePicker({
trigger: '#date'
});

Y.one('#icon').on('click', function(event) {
// Cannot do datePicker.show(); because of AUI-1795
var date = document.getElementById('date');
date.focus();
date.click();
});
});
</script>


Runnable JSFiddle of this example.

- Kyle
Low Trux, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Junior Member Mensajes: 64 Fecha de incorporación: 6/11/14 Mensajes recientes
Kyle Joseph Stiemann:
Alternatively, an even simpler way to do this (which may or may not fit your use case) is to set the input as the trigger of the DatePicker, but have the icon show the DatePicker on click:

<i id="icon" class="icon-calendar icon-1x"></i>
<input id="date" type="text" />
<script>
YUI().use('aui-datepicker', function (Y) {

var datePicker = new Y.DatePicker({
trigger: '#date'
});

Y.one('#icon').on('click', function(event) {
// Cannot do datePicker.show(); because of AUI-1795
var date = document.getElementById('date');
date.focus();
date.click();
});
});
</script>


Runnable JSFiddle of this example.

- Kyle


Thanks a lot Kyle, it worked ! Just one thing, i just want the icon to trigger the calendar but using this solution the input will also trigger the calendar, is there any way to make just the icon to trigger the calendar and make the input just get all the data from the calendar ?
mark grant, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

New Member Mensajes: 11 Fecha de incorporación: 10/01/15 Mensajes recientes
have you tried wrapping the code within the i tags? life insurance london uk
thumbnail
Kyle Joseph Stiemann, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Liferay Master Mensajes: 760 Fecha de incorporación: 14/01/13 Mensajes recientes
Thanks a lot Kyle, it worked ! Just one thing, i just want the icon to trigger the calendar but using this solution the input will also trigger the calendar, is there any way to make just the icon to trigger the calendar and make the input just get all the data from the calendar ?


If you want to use it that way, you'll have to use the first example that I posted from StackOverflow. It's a little more complex, but it should work. Just make sure you also correct the issues that I mentioned.

- Kyle
Low Trux, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Junior Member Mensajes: 64 Fecha de incorporación: 6/11/14 Mensajes recientes
Kyle Joseph Stiemann:
Thanks a lot Kyle, it worked ! Just one thing, i just want the icon to trigger the calendar but using this solution the input will also trigger the calendar, is there any way to make just the icon to trigger the calendar and make the input just get all the data from the calendar ?


If you want to use it that way, you'll have to use the first example that I posted from StackOverflow. It's a little more complex, but it should work. Just make sure you also correct the issues that I mentioned.

- Kyle


Ok Got it ! it's aaaallmost done, now it works the way i want BUT when i type the date and press enter the calendar wont reflect that date on the actual widget. When i open the calendar and click the date it will show that date on the input but when i type the date on the input it wont mark that date on the calendar, hope you can undestand this emoticon.

<div class="input_alta input_datepicker">
    <label><liferay-ui:message key="dataAlta" /></label>
    <i id="id_alta" class="icon-calendar icon-1x"></i>
    <input id="startDate" placeholder="dd/mm/aaaa" value="" type="text">
</div>			
<div class="input_fins input_datepicker">
   <label><liferay-ui:message key="fins" /></label>
    <i id="id_fins" class="icon-calendar icon-1x"></i>
    <input id="endDate" placeholder="dd/mm/aaaa" value="" type="text">
</div>


<aui:script>
YUI( { lang: 'ca-ES' } ).use(
		  'aui-datepicker',
  	 
	  function(Y) {
		  var input= Y.one('#startDate');
		  var datepickerAlta = new Y.DatePicker(
			      {
					trigger: '#id_alta',
			        mask: '%d/%m/%Y',
			        calendar: {
			        	on: {
			        		dateClick: function(event) {
			        			input.set('value', Y.Date.format(event.date,{format:datepickerAlta.get('mask')}));
			        		}
			        	}	
			        },
			        popover: {
			          zIndex: 1
			        },
	                after: {
	            		selectionChange: function(event) {
							fillTable('&lt;%=sessionBean.getEns().getIdEns() %&gt;');
			         	}
			      	}
			      }
			    );
		  
		  var input2= Y.one('#endDate');
		  var datepickerFins = new Y.DatePicker(
			      {
			        trigger: '#id_fins',
			        mask: '%d/%m/%Y',
			        calendar: {
			        	on: {
			        		dateClick: function(event) {
			        			input2.set('value', Y.Date.format(event.date,{format:datepickerFins.get('mask')}));
			        		}
			        	}	
			        },
			        popover: {
			          zIndex: 1
			        },
	            after: {
	            		selectionChange: function(event) {
							fillTable('&lt;%=sessionBean.getEns().getIdEns() %&gt;');
			         	}
			      	}
			      }
			    );
		  

		 /*To get date when pressing enter*/
		 Y.one('#startDate').on('change', function(event) {
			 fillTable('&lt;%=sessionBean.getEns().getIdEns() %&gt;');
			});
		 
		 Y.one('#id_fins').on('click', function(event) {
				// Cannot do datePicker.show(); because of AUI-1795
				var date = document.getElementById('endDate');
				date.focus();
				date.click();
				});
     	  
	}
);
</aui:script>
thumbnail
Kyle Joseph Stiemann, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Liferay Master Mensajes: 760 Fecha de incorporación: 14/01/13 Mensajes recientes
Great! Glad it's working for you.

...but when i type the date on the input it wont mark that date on the calendar...

Liferay Faces alloy.js file shows an example of how to update the DatePicker with the value of the input.

Also, you probably don't need the following lines anymore:

Y.one('#id_fins').on('click', function(event) {
// Cannot do datePicker.show(); because of AUI-1795
var date = document.getElementById('endDate');
date.focus();
date.click();
});


And you should make sure that your version of AlloyUI is not affected by AUI-1205. If it is, fillTable() will be called a bunch of extra times. If you need to work around AUI-1205, you can put fillTable() in your dateClick function.

- Kyle
Low Trux, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Junior Member Mensajes: 64 Fecha de incorporación: 6/11/14 Mensajes recientes
Kyle Joseph Stiemann:
Great! Glad it's working for you.

...but when i type the date on the input it wont mark that date on the calendar...

Liferay Faces alloy.js file shows an example of how to update the DatePicker with the value of the input.

Also, you probably don't need the following lines anymore:

Y.one('#id_fins').on('click', function(event) {
// Cannot do datePicker.show(); because of AUI-1795
var date = document.getElementById('endDate');
date.focus();
date.click();
});


And you should make sure that your version of AlloyUI is not affected by AUI-1205. If it is, fillTable() will be called a bunch of extra times. If you need to work around AUI-1205, you can put fillTable() in your dateClick function.

- Kyle



I did this and is working now:

var inputStart = Y.one('#startDate');
         inputStart.on('change', function(){
         var value = inputStart.get('value');

				if (value) {

					var mask = datepickerAlta.get('mask'),
					dateParser = new Y.DateParser(mask),
					date = dateParser.parse(value),
					button = Y.one(datepickerAlta.get('trigger')),
					calendar = datepickerAlta.getCalendar();

					value = '';
					calendar.deselectDates();

					if (date) {

						value = Y.Date.format(date,{format:mask});
						calendar.selectDates(date);
					}

					button.set('value', value);
					inputStart.set('value', value);
				}
			});
         
         var inputEnd = Y.one('#endDate');
         inputEnd.on('change', function(){
         var value = inputEnd.get('value');

				if (value) {

					var mask2 = datepickerFins.get('mask'),
					dateParser = new Y.DateParser(mask2),
					date2 = dateParser.parse(value),
					button2 = Y.one(datepickerFins.get('trigger')),
					calendar2 = datepickerFins.getCalendar();

					value = '';
					calendar2.deselectDates();

					if (date2) {

						value = Y.Date.format(date2,{format:mask2});
						calendar2.selectDates(date2);
					}

					button2.set('value', value);
					inputEnd.set('value', value);
				}
			}); 


Just one last question Kyle (i know, im really sorry): In order to compare those two values (begin date and end date) to send some error messages how do you get the values from the inputs ? I want to do something like :

if( inputEnd.value > inputStart.value) then alert ('End Date cannot be "bigger" than Start Date).

Many Thanks !
thumbnail
Kyle Joseph Stiemann, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Liferay Master Mensajes: 760 Fecha de incorporación: 14/01/13 Mensajes recientes
In order to compare those two values (begin date and end date) to send some error messages how do you get the values from the inputs ?

You should call DatePicker.getSelectedDates() on both DatePickers and compare them with javascript operators:

var startDate = start.getSelectedDates();
var endDate = end.getSelectedDates();

if (!startDate || !endDate || (startDate < endDate)) {
alert("Valid!");
} else {
alert("Invalid!");
}


Here's a runnable JSFiddle example.

- Kyle
Low Trux, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Junior Member Mensajes: 64 Fecha de incorporación: 6/11/14 Mensajes recientes
Great ! Thanks a lot Kyle.
thumbnail
Kyle Joseph Stiemann, modificado hace 9 años.

RE: DatePicker rendering on a specific input field

Liferay Master Mensajes: 760 Fecha de incorporación: 14/01/13 Mensajes recientes
Glad I could help. Thanks for using AlloyUI!

- Kyle
Low Trux, modificado hace 8 años.

RE: DatePicker rendering on a specific input field

Junior Member Mensajes: 64 Fecha de incorporación: 6/11/14 Mensajes recientes
Kyle Joseph Stiemann:
Glad I could help. Thanks for using AlloyUI!

- Kyle



Hello Kyle, when checking all of the above procedure on IE8 with Win XP apparently the browser won't render all of the DataTable functionalities. When i click on the calendar it shows a "dataTable is not defined" message and won't load the records on the table (data by default is loaded tho). Also i have noticed that none of the YUI code that i use to work with the dom is working, not even the paginator (when i inspect the elements on IE8 the UL container is empty). Do you have any idea what's going on ?

This is the code i use to load the data table and the calendars:

YUI({ lang: 'ca-ES' }).use(
			'aui-datatable',
			'aui-pagination',
			'datatype-date',
			function(Y) {
				
				var truncate = function (o) {
					var trunc = '';
					if (o.value == "No") {
					 trunc = '';
					} else {
						trunc = '<i class="icon-bolt icon-1x"></i>';
					}
					return trunc;
				};
				
				function formatDate(cell) {
				    return Y.DataType.Date.format(new Date(cell.value), { format: '%d/%m/%Y' });
				}
				
				var nestedCols = [             
	       	  	  	{
	       	  	  	key:'DocumentIdTr',
	       	  	  	sortable: true
	       	  	  	},
	       	  	  	
	       	  	  	{
	       	  	  	key:'Titol',
	       	  	  	label:'Títol',
	       	  	  	sortable: true
	       	  	  	},
	       	  	  	
	       	  	    {
	       	  	  	key:'Urgent',
	       	  	  	allowHTML: true,
	       	  	  	formatter: truncate,
	       	  	  	label:'Urgent'
	       	  	  	},
	       	  	  	
	       	  	    {
	       	  	  	key:'Codi_Sollicitud',
	       	  	  	label: 'Codi Sol·licitud',
	       	  	  	sortable: true
	       	  	  	},
	       	  	  	
	       	  	    {
	       	 	  	key:'Data_Alta',
	       	 	    label: 'Data alta',
	       	  	  	sortable: true,
	       	  	  	formatter: formatDate
	       	  	  	}
	       	  	  	
	       	    ];
				
				numDataTable = document.getElementById("myDataTable").childNodes.length;
				
				if (numDataTable &gt; 0){
					dataTable.set('data', dataStore);
				} else {
					dataTable = new Y.DataTable (
				    	      {
				    	        columns: nestedCols,
				    	        data: dataStore,
				    	        plugins: [
			    	                  {fn: Y.Plugin.DataTableHighlight}
			   	                ],
					   	        rendered: true
				    	      }
					    ).render("#myDataTable");
				}
				
				//Control de Mensaje Alertaa
				var alerta  = document.getElementById("myAlert");
				
				if (entradas.length &lt;= 0){
	  	    		alerta.style.display = 'block';
	  	    	} else {
	  	    		alerta.style.display = 'none';
	  	    	}
				
				
				//Añadimos clases a la tabla para poder customizarla//
			  	 var nodeObject = Y.one('#myDataTable table');
			  	 nodeObject.removeClass('table-table');
			  	 nodeObject.addClass('table');
			  	 nodeObject.addClass('mytable');
			  	 nodeObject.addClass('table-hover');
			  	 
			  	 /*Asignamos id's a las columnas de las tablas*/
			  	 var documentIdTr = Y.one('#myDataTable table thead tr th:nth-child(1)');
			  	 var titol = Y.one('#myDataTable table thead tr th:nth-child(2)');
			  	 var urgent = Y.one('#myDataTable table thead tr th:nth-child(3)');
			  	 var codi_solicitud = Y.one('#myDataTable table thead tr th:nth-child(4)');
		  	     var data_alta = Y.one('#myDataTable table thead tr th:nth-child(5)');
		  	     documentIdTr.addClass('DocumentIdTr_col');
		  	     titol.addClass('titol_col');
		  	     urgent.addClass('urgent_col');
		  	     codi_solicitud.addClass('codi_solicitud_col');
		  	     data_alta.addClass('data_alta_col');
		  	     
		  	     dataTable.delegate('click',function(ev) {
					var target = ev.currentTarget, 
					//modelList = this.get('data'),
					columns = this.get('columns'),
					//cellIndex = Y.Node.getDOMNode(target).cellIndex,
					rid = target.get('id'),
					r1 = this.getRecord(rid);
					var selectedColumn = columns[0].key;   
					var selectedCell = r1.get(selectedColumn); 
					
					var petId = selectedCell;
					DWRUtil.setValue("frmConsulta:id",petId);
					document.getElementById("frmConsulta:botoConsulta").click();   
					
				},".table-cell",dataTable);
				
		  	     
		  	    function esVisible() {
		  	    	var num_page = document.getElementById("numResultsPage").value;
		  	    	var visible = false;
		  	    	
		  	    	if (num_page &lt; entradas.length &amp;&amp; entradas.length &gt; 0) {
		  	    		visible = true;
		  	    	}
		  	    	return visible;
		  	    }
		  	    
			  	new Y.Pagination({
			        boundingBox: '#pagination',
			        circular:false,
			        contentBox:'#pagination .pagination-content',
			        cssClass:'miclase',
			        page: 1,
			        visible: esVisible(),
			        on: {
			          changeRequest: function(event) {
			              dataTable.set('data', loadDataStore(xmlObject,event.state.page));
			          }
			        },
			        total:number_of_pages
			       
			      }).render();
			  	     
			  	  Y.one('.pagination-content .pagination-control:first-child').setHTML('<div><i class="icon-chevron-left icon-1x"></i></div>');   
			  	  Y.one('.pagination-content .pagination-control:last-child').setHTML('<div><i class="icon-chevron-right icon-1x"></i></div>');
			  	  //Ocultamos paginaci�n interna (1,2,3..etc)
			  	  Y.all('.pagination-content li:nth-of-type(n+2):nth-last-of-type(n+2)').addClass('ocultar');
			  	  ocultar = Y.all('.ocultar');
			  	  ocultar.setStyle('display','none');
			  	  //
			  	  prev = Y.one('.pagination-content li:first-child');
			  	  next = Y.one('.pagination-content li:last-child');
			  	  prev.setStyle('cursor','pointer');
			  	  next.setStyle('cursor','pointer');				
				
			  }
			);

	
	return "";
    
}


Also when loading the site i have this error :

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
Timestamp: Tue, 5 May 2015 07:38:27 UTC

Message: Invalid argument.
Line: 1
Char: 158696
Code: 0
URI: https://dev6.eacat.cat/html/js/everything.jsp?browserId=ie&themeId=eacat_WAR_eacattheme&colorSchemeId=01&minifierType=js&minifierBundleId=javascript.everything.files&languageId=ca_ES&b=6210&t=1426853346000

I have make my research and apparently the error is on the dom-style.js (liferay-portal-6.2.10.1-ee-ga1\tomcat-7.0.42\webapps\ROOT\html\js\aui\dom-style)
in this function:

 /**
     * Sets a style property for a given element.
     * @method setStyle
     * @param {HTMLElement} An HTMLElement to apply the style to.
     * @param {String} att The style property to set. 
     * @param {String|Number} val The value. 
     */
    setStyle: function(node, att, val, style) {
        style = style || node.style;
        var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES;

        if (style) {
            if (val === null || val === '') { // normalize unsetting
                val = '';
            } else if (!isNaN(new Number(val)) &amp;&amp; re_unit.test(att)) { // number values may need a unit
                val += Y_DOM.DEFAULT_UNIT;
            }

            if (att in CUSTOM_STYLES) {
                if (CUSTOM_STYLES[att].set) {
                    CUSTOM_STYLES[att].set(node, val, style);
                    return; // NOTE: return
                } else if (typeof CUSTOM_STYLES[att] === 'string') {
                    att = CUSTOM_STYLES[att];
                }
            } else if (att === '') { // unset inline styles
                att = 'cssText';
                val = '';
            }
           style[att] = val; 
        }
    },


Apparently the problem is caused in Line 30

Any help will be REALLY appreciated since im not able to find a solution and the portlet is not working at all in IE8 under Win XP. Many thanks !