year solo only mostrar months month meses mes bootstrap año and javascript jquery date jquery-ui jquery-ui-datepicker

javascript - solo - mes y año datepicker



jQuery UI DatePicker para mostrar solo el año del año (27)

¿Soy yo o esto no funciona como debería en IE (8)? La fecha cambia cuando se hace clic, pero el selector de fecha se abre de nuevo, hasta que realmente haces clic en algún lugar de la página para perder el foco en el campo de entrada ...

Estoy buscando resolver esto.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> <script type="text/javascript"> $(function() { $(''.date-picker'').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: ''MM yy'', onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker(''setDate'', new Date(year, month, 1)); } }); }); </script> <style> .ui-datepicker-calendar { display: none; } </style> </head> <body> <label for="startDate">Date :</label> <input name="startDate" id="startDate" class="date-picker" /> </body> </html>

Estoy usando el selector de fechas de jQuery para mostrar el calendario en toda mi aplicación. Quiero saber si puedo usarlo para mostrar el mes y el año (mayo de 2010) y no el calendario.


Añade una solución más simple

$(function() { $(''.monthYearPicker'').datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: ''M yy'' }).focus(function() { var thisCalendar = $(this); $(''.ui-datepicker-calendar'').detach(); $(''.ui-datepicker-close'').click(function() { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); thisCalendar.datepicker(''setDate'', new Date(year, month, 1)); }); }); });

http://jsfiddle.net/tmnasim/JLydp/
Caracteristicas :

  • mostrar solo mes / año
  • Agrega el valor del año del mes al cuadro de entrada solo al hacer clic en el botón Listo
  • No hay comportamiento de "reapertura" al hacer clic en "Hecho"
    ------------------------------------
    otra solución que funciona bien para datepicker y monthpicker en la misma página: (también evite el error de mutiple haciendo clic en el botón anterior en IE, que puede ocurrir si usamos la función de enfoque)
    JS fiddle link


Aquí hay un hack (actualizado con todo el archivo .html):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> <script type="text/javascript"> $(function() { $(''.date-picker'').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: ''MM yy'', onClose: function(dateText, inst) { $(this).datepicker(''setDate'', new Date(inst.selectedYear, inst.selectedMonth, 1)); } }); }); </script> <style> .ui-datepicker-calendar { display: none; } </style> </head> <body> <label for="startDate">Date :</label> <input name="startDate" id="startDate" class="date-picker" /> </body> </html>

EDITE jsfiddle para el ejemplo anterior: http://jsfiddle.net/DBpJe/7755/

EDITAR 2 Agrega el valor del año del mes al cuadro de entrada solo al hacer clic en el botón Hecho. También permite eliminar los valores del cuadro de entrada, lo que no es posible en el campo anterior http://jsfiddle.net/DBpJe/5103/

EDIT 3 actualizó la Solución Mejor basada en la solución de rexwolf.
http://jsfiddle.net/DBpJe/5106


Combiné muchas de las buenas respuestas anteriores y llego a esto:

$(''#payCardExpireDate'').datepicker( { dateFormat: "mm/yy", changeMonth: true, changeYear: true, showButtonPanel: true, onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker(''setDate'', new Date(year, month, 1)).trigger(''change''); }, beforeShow : function(input, inst) { if ((datestr = $(this).val()).length > 0) { year = datestr.substring(datestr.length-4, datestr.length); month = datestr.substring(0, 2); $(this).datepicker(''option'', ''defaultDate'', new Date(year, month-1, 1)); $(this).datepicker(''setDate'', new Date(year, month-1, 1)); } } }).focus(function () { $(".ui-datepicker-calendar").hide(); $("#ui-datepicker-div").position({ my: "center top", at: "center bottom", of: $(this) }); });

Se ha comprobado que esto funciona, pero al enfrentar muchos errores, me vi obligado a parchear en varios lugares del selector de fechas:

if($.datepicker._get(inst, "dateFormat") === "mm/yy") { $(".ui-datepicker-calendar").hide(); }

patch1: en _showDatepicker: para suavizar la piel;

patch2: en _checkOffset: para corregir el posicionamiento del selector de mes (de lo contrario, cuando el campo está en la parte inferior del navegador, la verificación de desplazamiento está desactivada);

patch3: en onClose of _hideDatepicker: de lo contrario, al cerrar los campos de fecha parpadeará durante un período muy corto, lo cual es muy molesto.

Sé que mi solución estaba lejos de ser buena, pero por ahora está funcionando. Espero eso ayude.


Como muchos otros, me he encontrado con numerosos problemas al intentar hacer esto, y solo una combinación de las soluciones publicadas y, finalmente, un gran truco para que sea perfecto, me ha dado una solución.

Problemas con otras soluciones en este hilo que he probado:

  1. La selección de una nueva fecha en un selector de fechas también cambiaría la fecha (interna) de otros seleccionadores de fechas, por lo que cuando abres de nuevo (o intentas obtener su fecha), tendrán una fecha diferente a la que se muestra en la entrada asignada. -campo.
  2. El selector de fechas no "recordaría" la fecha cuando se abriera de nuevo.
  3. El código para hacer malabares con las fechas utiliza la subcadena, por lo que no es compatible con todos los formatos.
  4. "Mi selector de mes" solo cambió el campo de entrada al cerrarlo, en lugar de cambiar los valores.
  5. El campo de entrada no se actualiza correctamente, si escribe una cadena de entrada con formato incorrecto para una fecha, y luego hace clic en ''Cerrar'' en el selector de fecha.
  6. No puedo tener seleccionadores de fecha normales, que muestran los días, en la misma página que seleccionadores de mes, que no muestran los días.

Finalmente he encontrado una manera de solucionar todos estos problemas . Los primeros cuatro pueden solucionarse simplemente teniendo cuidado de cómo hace referencia a sus seleccionadores de fecha y mes en su código interno y, por supuesto, realizando algunas actualizaciones manuales de sus selectores. Esto se puede ver en los ejemplos de instancias cerca del fondo. El quinto problema puede ser ayudado agregando un código personalizado a las funciones del selector de fecha.

NOTA: NO necesita usar los siguientes scripts de Selector de Meses para solucionar los tres primeros problemas en su seleccionador de fechas normal. Simplemente use el script de creación de instancias de datepicker cerca de la parte inferior de esta publicación.

Ahora, para usar monthpickers y reparar el último problema, necesitamos separar los datepickers y los mespickers. Podríamos obtener uno de los pocos complementos de jQuery-UI monthpicker, pero algunos carecen de flexibilidad / capacidad de localización, otros carecen de soporte de animación ... ¿qué hacer? ¡Rueda su "propio" desde el código del selector de fecha! Esto le proporciona un selector de mes completamente funcional, con todas las funcionalidades del selector de fecha, sin la visualización de días.

He suministrado el script js y el script CSS adjunto , con el método descrito a continuación, con el código jQuery-UI v1.11.1. Simplemente copie estos fragmentos de código en dos archivos nuevos, monthpicker.js y monthpicker.css, respectivamente.

Aquí está el proceso por el que pasé, para clonar el selector de fechas original y convertirlo en un seleccionador de meses.

Si no te importa cómo los hice, desplázate más allá de esta sección y baja a la línea "¡Ahora para agregar los seleccionadores de fechas y los seleccionadores de meses a la página!"

Tomé todo el código javascript de jquery-ui-1.11.1.js relacionado con su seleccionador de fechas, lo pegué en un nuevo archivo js y reemplacé las siguientes cadenas:

  • "datepicker" ==> monthpicker "
  • "Selector de fecha" ==> "Selector de mes"
  • "selector de fecha" ==> "selector de mes"
  • "Selector de fecha" ==> "Selector de mes"

Luego eliminé la parte del bucle for que crea la división de ui-datepicker-calendar (la otra solución se oculta mediante CSS). Esto se puede encontrar en la función _generateHTML: (inst).

Encuentra la línea que dice:

"</div><table class=''ui-datepicker-calendar''><thead>" +

Marque todo desde después de la etiqueta div de cierre y baje hasta (y no incluya) la línea donde dice:

drawMonth++;

Ahora será infeliz, porque necesitamos cerrar algunas cosas. Después de que cierre la etiqueta div de antes, agregue esto:

";

El código ahora debe estar bien unido. Aquí hay un fragmento de código que muestra lo que deberías haber terminado con:

...other code... calender += "<div class=''ui-monthpicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "''>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div>"; drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } ...other code...

Luego copié / pegué el código de jquery-ui.css correspondiente a los selectores de fechas en un nuevo archivo CSS, y reemplacé las siguientes cadenas:

  • "datepicker" ==> monthpicker "

¡Ahora para agregar los selectores de fechas y los seleccionadores de meses a la página!

¡Los siguientes fragmentos de código javascript funcionan con múltiples seleccionadores de fechas y / o seleccionadores de meses en la página, sin los problemas mencionados anteriormente! Solucionado generalmente usando ''$ (este)''. mucho :)

El primer script es para un selector de fechas normal, y el segundo es para los "nuevos" selectores de mes.

El comentario .after , que le permite crear algún elemento para borrar el campo de entrada, es robado de la respuesta de Paul Richards.

Estoy usando el formato "MM yy" en mi selector de mes, y el formato ''yy-mm-dd'' en mi seleccionador de fecha, pero esto es completamente compatible con todos los formatos , por lo que es libre de usar el que desee. Simplemente cambia la opción ''dateFormat''. Las opciones estándar ''showButtonPanel'', ''showAnim'' y ''yearRange'' son, por supuesto, opcionales y personalizables a sus deseos.

Añadiendo un selector de fecha

Creación de una instancia de datepicker. Éste va desde hace 90 años y hasta nuestros días. Le ayuda a mantener el campo de entrada correcto, especialmente si configura las opciones defaultDate, minDate y maxDate, pero puede manejarlo si no lo hace. Funcionará con cualquier fecha que elijas.

$(''#MyDateTextBox'').datepicker({ dateFormat: ''yy-mm-dd'', changeMonth: true, changeYear: true, showButtonPanel: true, showMonthAfterYear: true, showWeek: true, showAnim: "drop", constrainInput: true, yearRange: "-90:", minDate: new Date((new Date().getFullYear() - 90), new Date().getMonth(), new Date().getDate()), maxDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), defaultDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), onClose: function (dateText, inst) { // When onClose is called after we have clicked a day (and not clicked ''Close'' or outside the datepicker), the input-field is automatically // updated with a valid date-string. They will always pass, because minDate and maxDate are already enforced by the datepicker UI. // This try is to catch and handle the situations, where you open the datepicker, and manually type in an invalid date in the field, // and then close the datepicker by clicking outside the datepicker, or click ''Close'', in which case no validation takes place. try { // If datepicker can parse the date using our formatstring, the instance will automatically parse // and apply it for us (after the onClose is done). // If the input-string is invalid, ''parseDate'' will throw an exception, and go to our catch. // If the input-string is EMPTY, then ''parseDate'' will NOT throw an exception, but simply return null! var typedDate = $.datepicker.parseDate($(this).datepicker(''option'', ''dateFormat''), $(this).val()); // typedDate will be null if the entered string is empty. Throwing an exception will force the datepicker to // reset to the last set default date. // You may want to just leave the input-field empty, in which case you should replace ''throw "No date selected";'' with ''return;'' if (typedDate == null)throw "No date selected"; // We do a manual check to see if the date is within minDate and maxDate, if they are defined. // If all goes well, the default date is set to the new date, and datepicker will apply the date for us. var minDate = $(this).datepicker("option", "minDate"); var maxDate = $(this).datepicker("option", "maxDate"); if (minDate !== null && typedDate < minDate) throw "Date is lower than minDate!"; if (maxDate !== null && typedDate > maxDate) throw "Date is higher than maxDate!"; // We update the default date, because the date seems valid. // We do not need to manually update the input-field, as datepicker has already done this automatically. $(this).datepicker(''option'', ''defaultDate'', typedDate); } catch (err) { console.log("onClose: " + err); // Standard behavior is that datepicker does nothing to fix the value of the input field, until you choose // a new valid date, by clicking on a day. // Instead, we set the current date, as well as the value of the input-field, to the last selected (and // accepted/validated) date from the datepicker, by getting its default date. This only works, because // we manually change the default date of the datepicker whenever a new date is selected, in both ''beforeShow'' // and ''onClose''. var date = $(this).datepicker(''option'', ''defaultDate''); $(this).val($.datepicker.formatDate($(this).datepicker(''option'', ''dateFormat''), date)); $(this).datepicker(''setDate'', date); } }, beforeShow: function (input, inst) { // beforeShow is particularly irritating when initializing the input-field with a date-string. // The date-string will be parsed, and used to set the currently selected date in the datepicker. // BUT, if it is outside the scope of the minDate and maxDate, the text in the input-field is not // automatically updated, only the internal selected date, until you choose a new date (or, because // of our onClose function, whenever you click close or click outside the datepicker). // We want the input-field to always show the date that is currently chosen in our datepicker, // so we do some checks to see if it needs updating. This may not catch ALL cases, but these are // the primary ones: invalid date-format; date is too early; date is too late. try { // If datepicker can parse the date using our formatstring, the instance will automatically parse // and apply it for us (after the onClose is done). // If the input-string is invalid, ''parseDate'' will throw an exception, and go to our catch. // If the input-string is EMPTY, then ''parseDate'' will NOT throw an exception, but simply return null! var typedDate = $.datepicker.parseDate($(this).datepicker(''option'', ''dateFormat''), $(this).val()); // typedDate will be null if the entered string is empty. Throwing an exception will force the datepicker to // reset to the last set default date. // You may want to just leave the input-field empty, in which case you should replace ''throw "No date selected";'' with ''return;'' if (typedDate == null)throw "No date selected"; // We do a manual check to see if the date is within minDate and maxDate, if they are defined. // If all goes well, the default date is set to the new date, and datepicker will apply the date for us. var minDate = $(this).datepicker("option", "minDate"); var maxDate = $(this).datepicker("option", "maxDate"); if (minDate !== null && typedDate < minDate) throw "Date is lower than minDate!"; if (maxDate !== null && typedDate > maxDate) throw "Date is higher than maxDate!"; // We update the input-field, and the default date, because the date seems valid. // We also manually update the input-field, as datepicker does not automatically do this when opened. $(this).val($.datepicker.formatDate($(this).datepicker(''option'', ''dateFormat''), typedDate)); $(this).datepicker(''option'', ''defaultDate'', typedDate); } catch (err) { // Standard behavior is that datepicker does nothing to fix the value of the input field, until you choose // a new valid date, by clicking on a day. // We want the same behavior when opening the datepicker, so we set the current date, as well as the value // of the input-field, to the last selected (and accepted/validated) date from the datepicker, by getting // its default date. This only works, because we manually change the default date of the datepicker whenever // a new date is selected, in both ''beforeShow'' and ''onClose'', AND have a default date set in the datepicker options. var date = $(this).datepicker(''option'', ''defaultDate''); $(this).val($.datepicker.formatDate($(this).datepicker(''option'', ''dateFormat''), date)); $(this).datepicker(''setDate'', date); } } }) //.after( // this makes a link labeled "clear" appear to the right of the input-field, which clears the text in it // $("<a href=''javascript: void(0);''>clear</a>").click(function() { // $(this).prev().val(''''); // }) //) ;

Añadiendo un selector de mes

Incluya el archivo monthpicker.js y el archivo monthpicker.css en la página en la que desea utilizar el monthpickers.

Mensualización de Monthpicker El valor recuperado de este monthpicker, es siempre el PRIMER día del mes seleccionado. Comienza en el mes actual y abarca desde hace 100 años y 10 años en el futuro.

$(''#MyMonthTextBox'').monthpicker({ dateFormat: ''MM yy'', changeMonth: true, changeYear: true, showMonthAfterYear: true, showAnim: "drop", constrainInput: true, yearRange: "-100Y:+10Y", minDate: new Date(new Date().getFullYear() - 100, new Date().getMonth(), 1), maxDate: new Date((new Date().getFullYear() + 10), new Date().getMonth(), 1), defaultDate: new Date(new Date().getFullYear(), new Date().getMonth(), 1), // Monthpicker functions onClose: function (dateText, inst) { var date = new Date(inst.selectedYear, inst.selectedMonth, 1); $(this).monthpicker(''option'', ''defaultDate'', date); $(this).monthpicker(''setDate'', date); }, beforeShow: function (input, inst) { if ($(this).monthpicker("getDate") !== null) { // Making sure that the date set is the first of the month. if($(this).monthpicker("getDate").getDate() !== 1){ var date = new Date(inst.selectedYear, inst.selectedMonth, 1); $(this).monthpicker(''option'', ''defaultDate'', date); $(this).monthpicker(''setDate'', date); } } else { // If the date is null, we reset it to the defaultDate. Make sure that the defaultDate is always set to the first of the month! $(this).monthpicker(''setDate'', $(this).monthpicker(''option'', ''defaultDate'')); } }, // Special monthpicker function! onChangeMonthYear: function (year, month, inst) { $(this).val($.monthpicker.formatDate($(this).monthpicker(''option'', ''dateFormat''), new Date(year, month - 1, 1))); } }) //.after( // this makes a link labeled "clear" appear to the right of the input-field, which clears the text in it // $("<a href=''javascript: void(0);''>clear</a>").click(function() { // $(this).prev().val(''''); // }) //) ;

¡Eso es! Eso es todo lo que necesitas para hacer un mes.

Parece que no puedo hacer funcionar un jsfiddle con esto, pero está funcionando para mí en mi proyecto ASP.NET MVC. Simplemente haga lo que normalmente hace para agregar un selector de fecha a su página e incorpore los scripts anteriores, posiblemente cambiando el selector (que significa $ ("# MyMonthTextBox")) a algo que funcione para usted.

Espero que esto ayude a alguien.

Enlaces a pastebins para algunas configuraciones extra de fecha y mes seleccionador:

  1. Monthpicker trabajando el último día del mes . La fecha que reciba de este selector de mes siempre será el último día del mes.

  2. Dos seleccionadores de mes colaboradores ; ''start'' está trabajando el primer día del mes y ''end'' está trabajando el último mes. Ambos están restringidos entre sí, por lo que elegir un mes en "final" que es anterior al mes seleccionado en "inicio", cambiará "inicio" para que sea el mismo mes que "finalizar". Y viceversa.OPCIONAL: Al seleccionar un mes en ''inicio'', la ''fecha mínima'' se establece en ''final''. Para eliminar esta función, comente una línea en onClose (lea los comentarios).

  3. Dos recolectores de fechas que colaboran ; Ambos están restringidos entre sí, por lo que elegir una fecha en "final" que sea anterior a la fecha seleccionada en "inicio" cambiará "inicio" para que sea el mismo mes que "finalizar". Y viceversa.OPCIONAL: Al seleccionar una fecha en ''inicio'', la ''fecha mínima'' se establece en ''final''. Para eliminar esta función, comente una línea en onClose (lea los comentarios).


Este code está funcionando perfectamente para mí:

<script type="text/javascript"> $(document).ready(function() { $(".monthPicker").datepicker({ dateFormat: ''MM yy'', changeMonth: true, changeYear: true, showButtonPanel: true, onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).val($.datepicker.formatDate(''MM yy'', new Date(year, month, 1))); } }); $(".monthPicker").focus(function () { $(".ui-datepicker-calendar").hide(); $("#ui-datepicker-div").position({ my: "center top", at: "center bottom", of: $(this) }); }); }); </script> <label for="month">Month: </label> <input type="text" id="month" name="month" class="monthPicker" />

La salida es:


Esto es lo que se me ocurrió. Oculta el calendario sin necesidad de un bloque de estilo adicional y agrega un botón claro para solucionar el problema de no poder borrar el valor una vez que hace clic en la entrada. También funciona bien con varios selectores de mes en la misma página.

HTML:

<input type=''text'' class=''monthpicker''>

JavaScript:

$(".monthpicker").datepicker({ changeMonth: true, changeYear: true, dateFormat: "yy-mm", showButtonPanel: true, currentText: "This Month", onChangeMonthYear: function (year, month, inst) { $(this).val($.datepicker.formatDate(''yy-mm'', new Date(year, month - 1, 1))); }, onClose: function(dateText, inst) { var month = $(".ui-datepicker-month :selected").val(); var year = $(".ui-datepicker-year :selected").val(); $(this).val($.datepicker.formatDate(''yy-mm'', new Date(year, month, 1))); } }).focus(function () { $(".ui-datepicker-calendar").hide(); }).after( $("<a href=''javascript: void(0);''>clear</a>").click(function() { $(this).prev().val(''''); }) );


Hice un par de refinamientos a la respuesta casi perfecta de BrianS mencionada anteriormente:

  1. He ajustado de nuevo el valor establecido en el programa porque creo que en realidad lo hace un poco más legible en este caso (aunque tenga en cuenta que estoy usando un formato ligeramente diferente)

  2. Mi cliente no quería ningún calendario, así que he agregado una adición de clase en mostrar / ocultar para hacerlo sin afectar a ningún otro seleccionador de fechas. La eliminación de la clase se realiza en un temporizador para evitar que la tabla vuelva a aparecer cuando el selector de fechas se desvanece, lo que parece ser muy notable en IE.

EDITAR: Un problema que queda por resolver con esto es que no hay forma de vaciar el selector de fecha: borre el campo y haga clic en el botón de distancia y se vuelve a llenar con la fecha seleccionada.

EDIT2: no logré resolverlo bien (es decir, sin agregar un botón Borrar separado al lado de la entrada), así que terminé usando esto: https://github.com/thebrowser/jquery.ui.monthpicker - si alguien puede obtener la interfaz de usuario estándar uno para hacerlo que sería increíble.

$(''.typeof__monthpicker'').datepicker({ dateFormat: ''mm/yy'', showButtonPanel:true, beforeShow: function(input, dpicker) { if(/^(/d/d)//(/d/d/d/d)$/.exec($(this).val())) { var d = new Date(RegExp.$2, parseInt(RegExp.$1, 10) - 1, 1); $(this).datepicker(''option'', ''defaultDate'', d); $(this).datepicker(''setDate'', d); } $(''#ui-datepicker-div'').addClass(''month_only''); }, onClose: function(dt, dpicker) { setTimeout(function() { $(''#ui-datepicker-div'').removeClass(''month_only'') }, 250); var m = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var y = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker(''setDate'', new Date(y, m, 1)); } });

También necesitas esta regla de estilo:

#ui-datepicker-div.month_only .ui-datepicker-calendar { display:none }



Las respuestas anteriores son bastante buenas. Mi única queja es que no se puede borrar el valor una vez que se ha establecido. También prefiero el enfoque extens-jquery-like-a-plugin.

Esto funciona perfecto para mí:

$.fn.monthYearPicker = function(options) { options = $.extend({ dateFormat: "MM yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "" }, options); function hideDaysFromCalendar() { var thisCalendar = $(this); $(''.ui-datepicker-calendar'').detach(); // Also fix the click event on the Done button. $(''.ui-datepicker-close'').unbind("click").click(function() { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); thisCalendar.datepicker(''setDate'', new Date(year, month, 1)); }); } $(this).datepicker(options).focus(hideDaysFromCalendar); }

Entonces invoca así:

$(''input.monthYearPicker'').monthYearPicker();


Necesitaba un selector de mes / año para dos campos (desde y hasta) y cuando se eligió uno, el máximo / mínimo se fijó en el otro ... las fechas de los boletos de la aerolínea. Estaba teniendo problemas para establecer el máximo y mínimo ... las fechas del otro campo se borrarían. Gracias a varias de las publicaciones anteriores ... finalmente lo descubrí. Tienes que configurar opciones y fechas en un orden muy específico.

Vea este violín para la solución completa: Selector de mes / año @ JSFiddle

Código:

var searchMinDate = "-2y"; var searchMaxDate = "-1m"; if ((new Date()).getDate() <= 5) { searchMaxDate = "-2m"; } $("#txtFrom").datepicker({ dateFormat: "M yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "", minDate: searchMinDate, maxDate: searchMaxDate, showButtonPanel: true, beforeShow: function (input, inst) { if ((datestr = $("#txtFrom").val()).length > 0) { var year = datestr.substring(datestr.length - 4, datestr.length); var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), "#txtFrom").datepicker(''option'', ''monthNamesShort'')); $("#txtFrom").datepicker(''option'', ''defaultDate'', new Date(year, month, 1)); $("#txtFrom").datepicker(''setDate'', new Date(year, month, 1)); } }, onClose: function (input, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $("#txtFrom").datepicker(''option'', ''defaultDate'', new Date(year, month, 1)); $("#txtFrom").datepicker(''setDate'', new Date(year, month, 1)); var to = $("#txtTo").val(); $("#txtTo").datepicker(''option'', ''minDate'', new Date(year, month, 1)); if (to.length > 0) { var toyear = to.substring(to.length - 4, to.length); var tomonth = jQuery.inArray(to.substring(0, to.length - 5), $("#txtTo").datepicker(''option'', ''monthNamesShort'')); $("#txtTo").datepicker(''option'', ''defaultDate'', new Date(toyear, tomonth, 1)); $("#txtTo").datepicker(''setDate'', new Date(toyear, tomonth, 1)); } } }); $("#txtTo").datepicker({ dateFormat: "M yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "", minDate: searchMinDate, maxDate: searchMaxDate, showButtonPanel: true, beforeShow: function (input, inst) { if ((datestr = $("#txtTo").val()).length > 0) { var year = datestr.substring(datestr.length - 4, datestr.length); var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), $("#txtTo").datepicker(''option'', ''monthNamesShort'')); $("#txtTo").datepicker(''option'', ''defaultDate'', new Date(year, month, 1)); $("#txtTo").datepicker(''setDate'', new Date(year, month, 1)); } }, onClose: function (input, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $("#txtTo").datepicker(''option'', ''defaultDate'', new Date(year, month, 1)); $("#txtTo").datepicker(''setDate'', new Date(year, month, 1)); var from = $("#txtFrom").val(); $("#txtFrom").datepicker(''option'', ''maxDate'', new Date(year, month, 1)); if (from.length > 0) { var fryear = from.substring(from.length - 4, from.length); var frmonth = jQuery.inArray(from.substring(0, from.length - 5), $("#txtFrom").datepicker(''option'', ''monthNamesShort'')); $("#txtFrom").datepicker(''option'', ''defaultDate'', new Date(fryear, frmonth, 1)); $("#txtFrom").datepicker(''setDate'', new Date(fryear, frmonth, 1)); } } });

También agregue esto a un bloque de estilo como se mencionó anteriormente:

.ui-datepicker-calendar { display: none !important; }


Si alguien quiere eso, también para calendarios múltiples no es muy difícil agregar esta funcionalidad a jQuery ui. con búsqueda minified para:

x+=''<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix''+t+''">''+(/all|left/.test(t)&&C==0?c?f:n:"")+(

agrega esto delante de x

var accl = ''''; if(this._get(a,"justMonth")) {accl = '' ui-datepicker-just_month'';}

buscar

<table class="ui-datepicker-calendar

y reemplazarlo con

<table class="ui-datepicker-calendar''+accl+''

tambien busca

this._defaults={

reemplazarlo con

this._defaults={justMonth:false,

para css debes usar:

.ui-datepicker table.ui-datepicker-just_month{ display: none; }

después de eso, todo está listo, vaya a las funciones de inicio del selector de fecha que desee y proporcione la configuración var

$(''#txt_month_chart_view'').datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: ''MM yy'', justMonth: true, create: function(input, inst) { $(".ui-datepicker table").addClass("badbad"); }, onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker(''setDate'', new Date(year, month, 1)); } });

justMonth: true es la clave aquí :)



Tuve el problema del selector de fecha mezclado con el selector de mes. Así lo resolví.

$(''.monthpicker'').focus(function() { $(".ui-datepicker-calendar").show(); }).datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: ''MM/yy'', create: function (input, inst) { }, onClose: function(dateText, inst) { var month = 1+parseInt($("#ui-datepicker-div .ui-datepicker-month :selected").val()); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); } });


después de cavar jQueryUI.com para datepicker, aquí está mi conclusión y respuesta a su pregunta.

Primero, diría que no a tu pregunta. No puede usar jQueryUI datepicker para elegir solo mes y año. No es compatible. No tiene función de devolución de llamada para eso.

Pero puede piratearlo para mostrar solo el mes y el año usando css para ocultar los días, etc. Y creo que no tendrá sentido, ya que necesita que haga clic en las fechas para elegir una fecha.

Puedo decir que solo tienes que usar otro selector de fechas. Como lo que Roger sugirió.


@Ben Koehler , ¡eso es prefecto! Hice una pequeña modificación para que el uso de una sola instancia del selector de fecha funcione más de una vez como se esperaba. Sin esta modificación, la fecha se analiza incorrectamente y la fecha seleccionada previamente no se resalta.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> <script type="text/javascript"> $(function() { $(''.date-picker'').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: ''MM yy'', onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker(''setDate'', new Date(year, month, 1)); }, beforeShow : function(input, inst) { var datestr; if ((datestr = $(this).val()).length > 0) { year = datestr.substring(datestr.length-4, datestr.length); month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker(''option'', ''monthNamesShort'')); $(this).datepicker(''option'', ''defaultDate'', new Date(year, month, 1)); $(this).datepicker(''setDate'', new Date(year, month, 1)); } } }); }); </script> <style> .ui-datepicker-calendar { display: none; } </style> </head> <body> <label for="startDate">Date :</label> <input name="startDate" id="startDate" class="date-picker" /> </body> </html>


Gracias por la solución de Ben Koehler.

Sin embargo, tuve un problema con varias instancias de seleccionadores de fechas, y algunas de ellas eran necesarias con la selección del día. La solución de Ben Koehler (en la edición 3) funciona, pero oculta la selección del día en todos los casos. Aquí hay una actualización que resuelve este problema:

$(''.date-picker'').datepicker({ dateFormat: "mm/yy", changeMonth: true, changeYear: true, showButtonPanel: true, onClose: function(dateText, inst) { if($(''#ui-datepicker-div'').html().indexOf(''ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover'') > -1) { $(this).datepicker( ''setDate'', new Date( $("#ui-datepicker-div .ui-datepicker-year :selected").val(), $("#ui-datepicker-div .ui-datepicker-month :selected").val(), 1 ) ).trigger(''change''); $(''.date-picker'').focusout(); } $("#ui-datepicker-div").removeClass("month_year_datepicker"); }, beforeShow : function(input, inst) { if((datestr = $(this).val()).length > 0) { year = datestr.substring(datestr.length-4, datestr.length); month = datestr.substring(0, 2); $(this).datepicker(''option'', ''defaultDate'', new Date(year, month-1, 1)); $(this).datepicker(''setDate'', new Date(year, month-1, 1)); $("#ui-datepicker-div").addClass("month_year_datepicker"); } } });


Probé las diversas soluciones proporcionadas aquí y funcionaron bien si simplemente deseaba un par de menús desplegables.

El mejor "selector" (en apariencia, etc.) ( https://github.com/thebrowser/jquery.ui.monthpicker ) sugerido aquí es básicamente una copia de una versión antigua de jquery-ui datepicker con el _generateHTML reescrito. Sin embargo, encontré que ya no se reproduce bien con jquery-ui actual (1.10.2) y tuve otros problemas (no se cierra en esc, no se cierra en la apertura de otros widgets, tiene estilos codificados).

En lugar de intentar corregir ese selector de mes y de intentar reintentar el mismo proceso con el último selector de fecha, me conecté a las partes relevantes del selector de fechas existente.

Esto implica anular:

  • _generateHTML (para construir el marcador del selector de mes)
  • ParseDate (ya que no le gusta cuando no hay componente de día),
  • _selectDay (ya que datepicker usa .html () para obtener el valor del día)

Como esta pregunta es un poco antigua y ya está bien respondida, aquí solo se muestra la anulación de _selectDay para mostrar cómo se hizo esto:

jQuery.datepicker._base_parseDate = jQuery.datepicker._base_parseDate || jQuery.datepicker.parseDate; jQuery.datepicker.parseDate = function (format, value, settings) { if (format != "M y") return jQuery.datepicker._hvnbase_parseDate(format, value, settings); // "M y" on parse gives error as doesn''t have a day value, so ''hack'' it by simply adding a day component return jQuery.datepicker._hvnbase_parseDate("d " + format, "1 " + value, settings); };

Como se dijo, esta es una pregunta antigua, pero me pareció útil, así que quería agregar comentarios con una solución alternativa.


Todos aquí están obteniendo valor de mes, año como este,

var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var month = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

Pero justo ahora me enfrento a un problema mientras obtengo valores de >y <. Porque nos da el valor del valor seleccionado en el menú desplegable, por lo que nos proporciona oldvalor no newvalores.

Por lo tanto, según el documento de Jquery UI: - http://api.jqueryui.com/datepicker/ . Podemos obtener directamente el año, el mes de la función. Para otros valores como dayetc., podemos acceder fácilmente a ellos a través del objeto de jqueryUIfunción. Podemos acceder a inst como abajo,

var day = inst.selectedDay;

Por lo tanto, al usar onChangeMonthYearpodemos obtener los valores actuales del mes, año y día directamente desde la función, por lo que no es necesario trabajar para el valor seleccionado.

HTML: -

<input type=''text'' class=''monthpicker''>

Guión: -

$( function() { $(".monthPicker").datepicker({ dateFormat: ''MM yy'', changeMonth: true, changeYear: true, showButtonPanel: true, beforeShow: true, onChangeMonthYear: function(year , month , inst) { setTimeout(function() { $(''.ui-datepicker-calendar'').hide(); }); var day = inst.selectedDay; month = month; year = year; var current_date = year + "-" + month + "-" + day ; } }); $(".monthPicker").focus(function () { $(".ui-datepicker-calendar").hide(); $("#ui-datepicker-div").position({ my: "center top", at: "center bottom", of: $(this) }); }); });

Nota: - Puede ser útil cuando queremos el selector de mes en línea. Simplemente reemplace el campo de entrada a la división y podemos usarlo en línea mientras usamos en línea, asegúrese de estar usando onChangeMonthYear,

Para el Selector de Mes en línea : -

<div class="monthpicker"> </div>


para un mespicker, utilizando JQuery v 1.7.2, tengo el siguiente javascript que está haciendo precisamente eso

$l("[id$=txtDtPicker]"). monthpicker ({
showOn: "both",
buttonImage: "../../images/Calendar.png",
buttonImageOnly: true,
pattern: ''yyyymm'', // Default is ''mm/yyyy'' and separator char is not mandatory
monthNames: [''Jan'', ''Fev'', ''Mar'', ''Abr'', ''Mai'', ''Jun'', ''Jul'', ''Ago'', ''Set'', ''Out'', ''Nov'', ''Dez'']
});


He tenido ciertas dificultades con la respuesta aceptada y ninguna otra podría usarse con un mínimo esfuerzo como base. Por lo tanto, decidí modificar la última versión de la respuesta aceptada hasta que cumpla al menos los estándares mínimos de codificación / reutilización JS.

Aquí hay una solución mucho más limpia que la http://jsfiddle.net/DBpJe/5106 de la respuesta aceptada de Ben Koehler . Además, lo hará:

  • Trabaje no solo con el mm/yyformato, sino con cualquier otro, incluidos los OP MM yy.
  • no ocultar el calendario de otros selectores de fechas en la página.
  • no contaminan implícitamente el objeto global con el JS datestr, month, yearetc variables.

Echale un vistazo:

$(''.date-picker'').datepicker({ dateFormat: ''MM yy'', changeMonth: true, changeYear: true, showButtonPanel: true, onClose: function (dateText, inst) { var isDonePressed = inst.dpDiv.find(''.ui-datepicker-close'').hasClass(''ui-state-hover''); if (!isDonePressed) return; var month = inst.dpDiv.find(''.ui-datepicker-month'').find('':selected'').val(), year = inst.dpDiv.find(''.ui-datepicker-year'').find('':selected'').val(); $(this).datepicker(''setDate'', new Date(year, month, 1)).change(); $(''.date-picker'').focusout(); }, beforeShow: function (input, inst) { var $this = $(this), // For the simplicity we suppose the dateFormat will be always without the day part, so we // manually add it since the $.datepicker.parseDate will throw if the date string doesn''t contain the day part dateFormat = ''d '' + $this.datepicker(''option'', ''dateFormat''), date; try { date = $.datepicker.parseDate(dateFormat, ''1 '' + $this.val()); } catch (ex) { return; } $this.datepicker(''option'', ''defaultDate'', date); $this.datepicker(''setDate'', date); inst.dpDiv.addClass(''datepicker-month-year''); } });

Y todo lo que necesitas es el siguiente CSS en algún lugar:

.datepicker-month-year .ui-datepicker-calendar { display: none; }

Eso es. Espero que lo anterior ahorre tiempo para otros lectores.


Me gustó la respuesta @ user1857829 y su enfoque de "extender jquery-like-a-plugin". Acabo de hacer una pequeña modificación para que cuando cambie el mes o el año de alguna manera, el selector escriba la fecha en el campo. Descubrí que me gustaría ese comportamiento después de usarlo un poco.

jQuery.fn.monthYearPicker = function(options) { options = $.extend({ dateFormat: "mm/yy", changeMonth: true, changeYear: true, showButtonPanel: true, showAnim: "", onChangeMonthYear: writeSelectedDate }, options); function writeSelectedDate(year, month, inst ){ var thisFormat = jQuery(this).datepicker("option", "dateFormat"); var d = jQuery.datepicker.formatDate(thisFormat, new Date(year, month-1, 1)); inst.input.val(d); } function hideDaysFromCalendar() { var thisCalendar = $(this); jQuery(''.ui-datepicker-calendar'').detach(); // Also fix the click event on the Done button. jQuery(''.ui-datepicker-close'').unbind("click").click(function() { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); thisCalendar.datepicker(''setDate'', new Date(year, month, 1)); thisCalendar.datepicker("hide"); }); } jQuery(this).datepicker(options).focus(hideDaysFromCalendar); }


Sé que es una respuesta tardía, pero tuve el mismo problema un par de días antes y vine con una solución agradable y fluida. Primero encontré a este gran recolector de fechas here

Luego acabo de actualizar la clase CSS (jquery.calendarPicker.css) que viene con el ejemplo como este:

.calMonth { /*border-bottom: 1px dashed #666; padding-bottom: 5px; margin-bottom: 5px;*/ } .calDay { display:none; }

El complemento activa un evento DateChanged cuando cambias algo, por lo que no importa que no hagas clic en un día (y se ajusta bien como selector de año y mes)

¡Espero eso ayude!



Utilice la onSelectdevolución de llamada y elimine la parte del año manualmente y configure el texto en el campo manualmente


<style> .ui-datepicker table{ display: none; }

<script type="text/javascript"> $(function() { $( "#manad" ).datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: ''yy-mm'', onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker(''setDate'', new Date(year, month, 1)); }, beforeShow : function(input, inst) { if ((datestr = $(this).val()).length > 0) { actDate = datestr.split(''-''); year = actDate[0]; month = actDate[1]-1; $(this).datepicker(''option'', ''defaultDate'', new Date(year, month)); $(this).datepicker(''setDate'', new Date(year, month)); } } }); });

Esto solucionará el problema =) Pero quería el tiempoFormato aaaa-mm

Aunque solo lo intenté en FF4