Código de JQuery - Datepicker en jquery para nuestro formulario

Imágen de perfil
Val: 293
Oro
Ha mantenido su posición en JQuery (en relación al último mes)
Gráfica de JQuery

Datepicker en jquery para nuestro formulariográfica de visualizaciones


JQuery

Publicado el 9 de Julio del 2014 por Xavi (548 códigos)
5.183 visualizaciones desde el 9 de Julio del 2014
Siguiendo el desarrollo del datapicker, aquí esta implementado para ser utilizado en un formulario. Unicamente tenemos que poner la clase "datepicker" en nuestro input, y automaticamente aparecera el datepicker al poner el obtener el foco.
El datepicker, mostrar la fecha que hay en el cuadro de texto (si la hay), y si modificamos dicha fecha, el datepicker se ira actualizando a medida que vayamos escribiendo la fecha.
Cuando pulsemos sobre una fecha o se pierda el foco del input, el datepicker se cerrara.

Versión 1
estrellaestrellaestrellaestrellaestrella(1)

Publicado el 9 de Julio del 2014gráfica de visualizaciones de la versión: Versión 1
5.184 visualizaciones desde el 9 de Julio del 2014
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

Puedes visualizar un ejemplo aquí

Este código es la continuación de: http://www.lawebdelprogramador.com/codigo/JQuery/2711-Calendario_en_jquery.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <script src="http://code.jquery.com/jquery-1.10.1.js" type="text/javascript"></script>
 
    <style>
		#datepicker {
			position:absolute;
			display: inline-block;
			padding: 10px;
			border: 1px solid #888;
			display:none;
			background:#fff;
		}
		#datepicker table {
			width:200px;
			font-family:Arial;
			font-size:12px;
			border-collapse: collapse;
		}
		#datepicker table caption {
			padding:5px 10px;
			background-color:#ddd;
			color:#444;
			font-weight:bold;
		}
		#datepicker table caption span {
			padding:2px;
		}
		#datepicker table caption span:nth-child(1) {
			float:left;
		}
		#datepicker table caption span:nth-child(3) {
			float:right;
		}
		#datepicker table caption span:nth-child(1), #datepicker table caption span:nth-child(3) {
			cursor:pointer;
		}
		#datepicker table caption span:nth-child(1):hover, #datepicker table caption span:nth-child(3):hover {
			background-color:#0073ea;
			color:#fff;
			-moz-border-radius:5px;-webkit-border-radius:5px;-o-border-radius:5px;border-radius:8px;
		}
		#datepicker table th {
			color:#444;
		}
		#datepicker table td {
			text-align:right;
			padding:5px;
			border-spacing: 2px;
			font-weight:bold;
		}
		#datepicker table td.d {
			border:1px solid #ccc;
			cursor:pointer;
			color:#0073ea;
		}
		#datepicker table td.d:hover {
			color:#fff;
			background-color:#0073ea;
		}
		#datepicker table td.today {
			color:#000;
		}
		#datepicker table td.select {
			color:#fb0000;
		}
	</style>
 
    <script>
		var months=Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
		var object;
 
		/**
		 * Funcion que devuelve true o false dependiendo de si la fecha es correcta.
		 * Tiene que recibir el dia, mes y año
		 *	http://lwp-l.com/s2379
		 */
		function isValidDate(day,month,year)
		{
			var dteDate;
			month=month-1;
			dteDate=new Date(year,month,day);
 
			//Devuelva true o false...
			return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));
		}
 
		/**
		 * Funcion para validar una fecha en español
		 */
		function checkDate(fecha)
		{
			var patron=new RegExp("^([0-9]{1,2})([/])([0-9]{1,2})([/])(19|20)+([0-9]{2})$");
 
			if(fecha.search(patron)==0)
			{
				var values=fecha.split("/");
				if(isValidDate(values[0],values[1],values[2]))
				{
					return true;
				}
			}
			return false;
		}
 
		$(document).ready(function()
		{
			$(".datepicker").focus(function(){
				if($("#datepicker").length && $('#datepicker').is(":hover"))
				{
				}else{
					if(checkDate($(this).val())==true)
					{
						var values=$(this).val().split("/");
						showCalendar(values[2],values[1]-1,values[0]);
					}else{
						showCalendar();
					}
					$("#datepicker").offset({top:$(this).offset().top+25, left:$(this).offset().left});
					object=$(this);
				}
			});
 
			/**
			 * Evento que se ejecuta cuando pierde el foco el cuadro de texto
			 * Cierra el datepicker cuando pierde el foco el cuadro
			 * de texto y no tenemos el cursor encima del datepicker
			 */
			$(".datepicker").blur(function(){
				if($('#datepicker').is(":hover"))
				{
				}else{
					// unicamente lo esconedemos si no estamos sobre el datapiker
					$("#datepicker").fadeOut();
				}
			});
			/**
			 * Evento que se ejecuta al soltar una tecla o modificar el cuadro
			 * de texto
			 * Si la fecha es correcta, modifica el datepicker para mostrar la 
			 * fecha escrita
			 */
			$(".datepicker").on("keyup change",function(){
				if(checkDate($(this).val())==true)
				{
					var values=$(this).val().split("/");
					showCalendar(values[2],values[1]-1,values[0]);
				}
			});
 
			/**
			 * Función que muestra el calendario
			 * Puede recibir el año, mes y dia a visualizar
			 */
			function showCalendar(year,month,day)
			{
				if($("#datepicker").length==0)
				{
					// not exists...
					$("body").append("<div id='datepicker'><table><caption></caption><thead><tr><th>Lu</th><th>Ma</th><th>Mi</th><th>Ju</th><th>Vi</th><th>Sa</th><th>Do</th></tr></thead><tbody></tbody></table></div>");
				}
				$("#datepicker").fadeIn();
 
				var now=new Date();
				var dayNow=now.getDate();
				var select=0
 
				if(year==undefined || month==undefined)
				{
					// obtenemos los valores actuales
					var d=new Date();
 
				}else{
					if(month==12)
					{
						month=0;
						year++;
					}
					if(month==-1)
					{
						month=11;
						year--;
					}
					var d=new Date(year,month);
					if(day!=undefined)
						select=day;
				}
				var monthShow=d.getMonth();
				var yearShow=d.getFullYear();
				var firstDayDate = new Date(d.getFullYear(), d.getMonth(), 1);
				var firstDay=firstDayDate.getDate();
				var dayWeek=firstDayDate.getDay()+7;
				var lastDayDate = new Date(d.getFullYear(), d.getMonth() + 1, 0);
				var lastDay=lastDayDate.getDate();
 
				$("#datepicker table caption").html("<span>&lt;&lt;</span><span>"+months[monthShow]+" "+yearShow+"</span><span>&gt;&gt;</span>");
				$("#datepicker table tbody tr").remove();
				$("#datepicker table tbody").append("<tr></tr>");
 
				var last_cell=dayWeek+lastDay
				var day=0;
				for(var i=1;i<=42;i++)
				{
					if(i==dayWeek)
					{
						// determinamos en que dia empieza
						day=1;
					}
					if(i<dayWeek || i>=last_cell)
					{
						// celda vacia
						$("#datepicker table tbody tr:last-child").append("<td></td>");
					}else{
						// mostramos el dia
						if(day==select)
							$("#datepicker table tbody tr:last-child").append("<td class='select d'>"+day+"</td>");
						else if(day==dayNow && monthShow==now.getMonth())
							$("#datepicker table tbody tr:last-child").append("<td class='today d'>"+day+"</td>");
						else
							$("#datepicker table tbody tr:last-child").append("<td class='d'>"+day+"</td>");
						day++;
					}
					// cuando llegamos al final de la semana, iniciamos una columna nueva
					if(i%7==0)
					{
						if(i>last_cell)
						{
							break;
						}
						$("#datepicker table tbody").append("<tr></tr>");
					}
				}
 
				// evento click encima de un dia
				$("#datepicker table .d").click(function(){
					object.val($(this).html()+"/"+(monthShow+1)+"/"+yearShow);
					$("#datepicker").fadeOut();
				});
 
				// pulsamos en el botón anterior mes
				$("#datepicker table caption span:first-child").click(function(){
					showCalendar(yearShow,monthShow-1)
					object.focus();
				});
				// pulsamos en el botón siguiente mes
				$("#datepicker table caption span:last-child").click(function(){
					showCalendar(yearShow,monthShow+1)
					object.focus();
				});
			}
		});
    </script>
</head>
 
<body>
 
Fecha1: <input type="text" name="fecha1" class="datepicker">
<br>Fecha2: <input type="text" name="fecha2" class="datepicker">
 
</body>
</html>



Comentarios sobre la versión: Versión 1 (1)

Imágen de perfil
21 de Noviembre del 2016
estrellaestrellaestrellaestrellaestrella
Excelente aporte solo una pregunta siempre se necesita un escript o hay que separar el código fuente o es un solo código
Responder

Comentar la versión: Versión 1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s2713