2011-12-02 123 views
71

Estoy tratando de tener una fecha Seleccione rango con el selector de fecha UI.Selector de fecha jQuery - deshabilitar fechas pasadas

en el campo desde/para que las personas no puedan ver o seleccionar fechas anteriores al día de hoy.

Este es mi código:

$(function() { 
    var dates = $("#from, #to").datepicker({ 
     defaultDate: "+1w", 
     changeMonth: true, 
     numberOfMonths: 1, 
     onSelect: function(selectedDate) { 
      var option = this.id == "from" ? "minDate" : "maxDate", 
       instance = $(this).data("datepicker"), 
       date = $.datepicker.parseDate(
        instance.settings.dateFormat || 
        $.datepicker._defaults.dateFormat, 
        selectedDate, instance.settings); 
      dates.not(this).datepicker("option", option, date); 
     } 
    }); 
}); 

¿Puede alguien decirme cómo desactivar las fechas anteriores a la fecha de la presente.

Respuesta

83

Debe crear un nuevo objeto de fecha y configurarlo como minDate al inicializar los datepickers

<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/> 

var dateToday = new Date(); 
var dates = $("#from, #to").datepicker({ 
    defaultDate: "+1w", 
    changeMonth: true, 
    numberOfMonths: 3, 
    minDate: dateToday, 
    onSelect: function(selectedDate) { 
     var option = this.id == "from" ? "minDate" : "maxDate", 
      instance = $(this).data("datepicker"), 
      date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings); 
     dates.not(this).datepicker("option", option, date); 
    } 
}); 

Editar - a partir de su comentario ahora funciona como se espera http://jsfiddle.net/nicolapeluchetti/dAyzq/1/

+2

quiero implementar una forma en que las personas no puedan elegir una fecha que haya pasado ..como ayer el día anterior, etc. Solo a partir de hoy y en adelante. –

+1

@HarshaMV actualicé mi respuesta, solo debe establecer minDate cuando inicialice los selectores de fecha –

+0

@PoweRoy He actualizado la respuesta después de su comentario –

65

Declara la variable dateToday y el uso de la fecha () para configurarlo ... luego use esa variable para asignar a minDate que es un parámetro de datepicker.

var dateToday = new Date(); 
$(function() { 
    $("#datepicker").datepicker({ 
     numberOfMonths: 3, 
     showButtonPanel: true, 
     minDate: dateToday 
    }); 
}); 

Eso es todo ... Por encima de respuesta fue muy útil ... sigan así chicos ..

+0

Gracias por esta información –

+0

Claro y directo respuesta .. Gracias – ASD

1

conjunto de atributos startDate del selector de fecha, funciona, a continuación es el código de trabajo

$(function(){ 
$('#datepicker').datepicker({ 
    startDate: '-0m' 
    //endDate: '+2d' 
}).on('changeDate', function(ev){ 
    $('#sDate1').text($('#datepicker').data('date')); 
    $('#datepicker').datepicker('hide'); 
}); 
}) 
2

jQuery API documentation - datepicker

La fecha mínima seleccionable. Cuando se establece en null, no hay un mínimo.

Múltiples tipos soportados:

Fecha: un objeto Date que contiene la fecha mínima.
Número: Un número de días a partir de hoy. Por ejemplo, 2 representa two days a partir de hoy y -1 representa yesterday.
Cadena: Una cadena en el formato definido por la opción dateFormat, o una fecha relativa.
Las fechas relativas deben contener pares de valores y períodos; los períodos válidos son y para years, m para months, w para weeks, y d para days. Por ejemplo, +1m +7d representa one month and seven days de today.

el fin de no mostrar fechas anteriores que no sean hoy

$('#datepicker').datepicker({minDate: 0}); 
0

usted tiene que declarar fecha actual en las variables de la misma familia

$(function() { 
    var date = new Date(); 
    var currentMonth = date.getMonth(); 
    var currentDate = date.getDate(); 
    var currentYear = date.getFullYear(); 
    $('#datepicker').datepicker({ 
    minDate: new Date(currentYear, currentMonth, currentDate) 
    }); 
}) 
40
$('#datepicker-dep').datepicker({ 
    minDate: 0 
}); 

minDate:0 funciona para mí.

7

sólo para añadir a esto:

Si también necesita evitar que el usuario escriba manualmente una fecha en el pasado, esta es una posible solución. Esto es lo que terminamos haciendo (en base a la respuesta de @Nicola Peluchetti)

var dateToday = new Date(); 

$("#myDatePickerInput").change(function() { 
    var updatedDate = $(this).val(); 
    var instance = $(this).data("datepicker"); 
    var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, updatedDate, instance.settings); 

    if (date < dateToday) { 
     $(this).datepicker("setDate", dateToday); 
    } 
}); 

Lo que esto hace es cambiar el valor a la fecha de hoy si el usuario escribe manualmente una fecha en el pasado.

+0

Gracias por compartir. Funciona bien. +1. – OO7

4

Live Demo, probar esto,

$('#from').datepicker(
    { 
     minDate: 0, 
     beforeShow: function() { 
     $(this).datepicker('option', 'maxDate', $('#to').val()); 
     } 
    }); 
    $('#to').datepicker(
    { 
     defaultDate: "+1w", 
     beforeShow: function() { 
     $(this).datepicker('option', 'minDate', $('#from').val()); 
     if ($('#from').val() === '') $(this).datepicker('option', 'minDate', 0);        
    } 
    }); 
2

"MinDate" atributo se debe utilizar para desactivar fechas pasadas en jQuery selector de fechas.

minDate: new Date() Or minDate: '0' is the key for this.

Ex: 

$(function() { 
    $("#datepicker").datepicker({minDate: new Date()}); 
}); 

O

$(function() { 
    $("#datepicker").datepicker({minDate: 0}); 
}); 
0
$("#date").datetimepicker({startDate:new Date()}).datetimepicker('update', new Date()); 

new Date(): función de obtener la fecha del día de hoy fecha anterior están bloqueados. 100% de trabajo

2

basta con sustituir el código:

código antiguo:

$("#dateSelect").datepicker({ 
    showOtherMonths: true, 
    selectOtherMonths: true, 
    changeMonth: true, 
    changeYear: true, 
    showButtonPanel: true, 
    dateFormat: 'yy-mm-dd' 

}); 

nuevo código:

$("#dateSelect").datepicker({ 
    showOtherMonths: true, 
    selectOtherMonths: true, 
    changeMonth: true, 
    changeYear: true, 
    showButtonPanel: true, 
    dateFormat: 'yy-mm-dd', 
    minDate: 0 
}); 
12

Utilice la opción "MinDate" para restringir la fecha más temprana permitida. El valor "0" significa hoy en día (0 días a partir de hoy):

$(document).ready(function() { 
     $("#txtdate").datepicker({ 
      minDate: 0, 
      // ... 
     }); 
    }); 

Docs aquí: http://api.jqueryui.com/datepicker/#option-minDate

1

Ésta es la manera fácil de hacer esto

$('#datepicker').datepicker('setStartDate', new Date()); 

También podemos desactivar días futuros

$('#datepicker').datepicker('setEndDate', new Date()); 
0

He creado la función para desactivar la fecha anterior, disa ble días flexibles de fin de semana (Como el sábado, domingo)

Estamos usando beforeShowDay método de jQuery UI datepicker plugin. fecha

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
var NotBeforeToday = function(date) { 
 
\t \t var now = new Date(); //this gets the current date and time 
 
\t \t if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6)) 
 
\t \t \t return [true,""]; 
 
\t \t if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6)) 
 
\t \t \t return [true,""]; 
 
\t \t if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6)) 
 
\t \t \t return [true,""]; 
 
\t \t return [false,""]; 
 
\t } 
 

 

 
jQuery("#datepicker").datepicker({ 
 
\t \t beforeShowDay: NotBeforeToday 
 
    });

enter image description here

Aquí de hoy es el 15 de septiembre He inhabilitado sábado y el domingo.

Cuestiones relacionadas