IT이야기

jQuery datepicker- 2 개의 입력 / 텍스트 상자 및 제한 범위

cyworld 2021. 4. 21. 21:24
반응형

jQuery datepicker- 2 개의 입력 / 텍스트 상자 및 제한 범위


두 개의 입력 상자가있는 jQuery Datepicker 위젯을 사용하고 있습니다. 하나는 "시작" 날짜이고 다른 하나는 " 종료 " 날짜입니다. 내가 사용하고 jQuery를 날짜 선택기 기능 데모 서로 일에 두 개의 입력 상자를 취득하기위한 기초로,하지만 나는이 추가 제한을 추가 할 수 있어야합니다 :

  1. 날짜 범위는 2008 년 12 월 1 일 이전 일 수 없습니다.

  2. "종료" 날짜는 오늘 이전 일 수 없습니다.

  3. a는 일단 "에서" 날짜를 선택하면 "받는 사람" 날짜 만 후 7 일의 범위 내에서 할 수있다 "에서" 날짜

  4. 경우 "받는 사람" 첫 번째 날짜를 선택 후 "에서" 날짜는 7 일 전의 범위 내에서 할 수있는 "사람" 날짜 (01 년 12 월 한도는 첫번째 선택 일 것 포함)

위의 모든 작업이 함께 작동하지 않는 것 같습니다.

요약하면 12 월 1 일부터 오늘까지 최대 7 일의 범위를 선택할 수 있기를 바랍니다 (12 월 1 일에 게시 할 예정이므로 현재는 오늘만받을 수 있음을 알고 있습니다).

지금까지 내 코드

$(function () {

$('#txtStartDate, #txtEndDate').datepicker(
            {
            showOn: "both",
            beforeShow: customRange,
            dateFormat: "dd M yy",
            firstDay: 1, 
            changeFirstDay: false
            });
});

function customRange(input) 
{ 

return {
         minDate: (input.id == "txtStartDate" ? new Date(2008, 12 - 1, 1) : null),
         minDate: (input.id == "txtEndDate" ? $("#txtStartDate").datepicker("getDate") : null), 
         maxDate: (input.id == "txtStartDate" ? $("#txtEndDate").datepicker("getDate") : null)
       }; 
}

7 일 범위 제한이 없으며 2008 년 12 월 1 일 이전 또는 오늘 이후에 " 종료 " 날짜를 선택할 수 없습니다. 어떤 도움이라도 대단히 감사하겠습니다, 감사합니다.


도움을 주셔서 감사합니다. Ben, 나는 귀하의 게시물을 작성하고 이것을 생각해 냈습니다. 이제 완성되었으며 훌륭하게 작동합니다!

다음은 작동 데모 입니다. 코드를 보려면 URL에 / edit추가 하십시오.

아래 완전한 코드-

$(function () 
{   
    $('#txtStartDate, #txtEndDate').datepicker({
        showOn: "both",
        beforeShow: customRange,
        dateFormat: "dd M yy",
        firstDay: 1, 
        changeFirstDay: false
    });

});

function customRange(input) { 
    var min = new Date(2008, 11 - 1, 1), //Set this to your absolute minimum date
        dateMin = min,
        dateMax = null,
        dayRange = 6; // Set this to the range of days you want to restrict to

    if (input.id === "txtStartDate") {
        if ($("#txtEndDate").datepicker("getDate") != null) {
            dateMax = $("#txtEndDate").datepicker("getDate");
            dateMin = $("#txtEndDate").datepicker("getDate");
            dateMin.setDate(dateMin.getDate() - dayRange);
            if (dateMin < min) {
                dateMin = min;
            }
        }
        else {
            dateMax = new Date; //Set this to your absolute maximum date
        }                      
    }
    else if (input.id === "txtEndDate") {
        dateMax = new Date; //Set this to your absolute maximum date
        if ($("#txtStartDate").datepicker("getDate") != null) {
            dateMin = $("#txtStartDate").datepicker("getDate");
            var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(),dateMin.getDate() + dayRange);

            if(rangeMax < dateMax) {
                dateMax = rangeMax; 
            }
        }
    }
    return {
        minDate: dateMin, 
        maxDate: dateMax
    };     
}

파티에 조금 늦었다는 것을 알고 있지만 여기에 작업 예제 코드를 수정 한 방법이 있습니다. 특정 최대 및 최소 날짜를 설정할 필요가 없었고 기간이 겹치는 것을 원하지 않았으므로 서로 설정하도록했습니다.

jQuery(function() {
  jQuery('#calendardatetime_required_to, #calendardatetime_required_from').datepicker('option', {
    beforeShow: customRange
  });
});

function customRange(input) {
  if (input.id == 'calendardatetime_required_to') {
    return {
      minDate: jQuery('#calendardatetime_required_from').datepicker("getDate")
    };
  } else if (input.id == 'calendardatetime_required_from') {
    return {
      maxDate: jQuery('#calendardatetime_required_to').datepicker("getDate")
    };
  }
}

(내 날짜 선택기는 이미 스크립트에서 초기화되었지만 기본 설정일뿐입니다.)

내가 필요한 일을 할 것 같습니다 :)

내 예는 여기참조 하십시오 .


좋습니다. 이건 어떨까요?

function customRange(input) 
{ 
    var min = new Date(2008, 12 - 1, 1);
    var dateMin = min;
    var dateMax = null;

    if (input.id == "txtStartDate" && $("#txtEndDate").datepicker("getDate") != null)
    {
        dateMax = $("#txtEndDate").datepicker("getDate");
        dateMin = $("#txtEndDate").datepicker("getDate");
        dateMin.setDate(dateMin.getDate() - 7);
        if (dateMin < min)
        {
            dateMin = min;
        }           
    }
    else if (input.id == "txtEndDate")
    {
        dateMax = new Date();
        if ($("#txtStartDate").datepicker("getDate") != null)
        {
            dateMin = $("#txtStartDate").datepicker("getDate");
            dateMax = $("#txtStartDate").datepicker("getDate");
            dateMax.setDate(dateMax.getDate() + 7); 
        }
    }
    return {
     minDate: dateMin, 
     maxDate: dateMax
   }; 

}

이것은 당신의 모든 요구 사항을 충족시키는 최선의 방법입니다 (제 생각에 ...)


두 개 대신 하나의 컨트롤을 사용하려면 rangeSelect를 사용하는 것이 좋습니다.

목표를 달성하려면 onSelect 리스너를 추가 한 다음 호출 datepicker( "option", settings )하여 설정을 변경 해야한다고 가정합니다 .


두 번째로 input.id를 확인할 때 두 번째 minDate가 null로 설정되기 때문에 txtStartDate의 시작 날짜가 작동하지 않습니다. 또한 maxDate는 txtStartDate가 아닌 txtEndDate를 확인해야합니다. 이 시도:

    function customRange(input) 
{ 
    var mDate = (input.id == "txtStartDate" ? new Date(2008, 12 - 1, 1) : $("#txtStartDate").datepicker("getDate"));
    return {
         minDate: mDate, 
         maxDate: (input.id == "txtEndDate" ? $("#txtStartDate").datepicker("getDate").getDate() + 5 : null)
       }; 
}

'+ 7'대신 '+ 5'가 왜 나타나는지 모르겠지만 0을 더하면 내가 선택한 날짜와 다음 날짜의 선택 가능한 날짜 범위가 표시됩니다.


다음은 제가 생각하는 공통적 인 문제에 대한 해결책을 찾기 위해 많은 파고를 한 후에 제가 생각 해낸 해결책입니다. 이것은 호환되는 일의 공유 입력 범위를 중심으로 입력을 효과적으로 '바운스'합니다. 의미-두 개의 필드가있는 경우 하나를 사용하여 다른 하나를 제한하고 다른 하나는 필요한 경우 원본을 재정의 할 수 있습니다. 이것의 목표는 항상 두 필드 사이에 유한 한 범위의 일 (또는 월 또는 기타) 만 있도록하는 것입니다. 이 특정 예는 또한 두 필드 (예 : 3 개월)에서 무언가를 선택할 수있는 미래의 시간을 제한합니다.


$("#startdate").datepicker({
   minDate: '+5', 
   maxDate: '+3M',
   changeMonth: true,
   showAnim: 'blind',
   onSelect: function(dateText, inst){ 

    // Capture the Date from User Selection
    var oldDate = new Date(dateText);
    var newDate = new Date(dateText);

    // Compute the Future Limiting Date
    newDate.setDate(newDate.getDate()+5);


    // Set the Widget Properties
    $("#enddate").datepicker('option', 'minDate', oldDate);
    $("#enddate").datepicker('option', 'maxDate', newDate);

    }
  });

 $("#enddate").datepicker({
  minDate: '+5',
  maxDate: '+3M',
  changeMonth: true,
  showAnim: 'blind', 
  onSelect: function(dateText, inst){ 

    // Capture the Date from User Selection
    var endDate = new Date(dateText);
    var startDate = new Date(dateText);

    // Compute the Future Limiting Date
    startDate.setDate(startDate.getDate()-5);

    // Set the Widget Properties
    $("#startdate").datepicker('option', 'minDate', startDate);
    $("#startdate").datepicker('option', 'maxDate', endDate);

    }

  });


이것이 내가 사용하는 방법입니다.

function customRange(input)
{
    var min = new Date();
    return {
        minDate: ((input.id == "txtStartDate") ? min : (input.id == "txtEndDate" ? $("#txtStartDate").datepicker("getDate") : null)),
        maxDate: (input.id == "txtStartDate" ? $("#txtEndDate").datepicker("getDate") : null)
    };
}

이것이 내가 한 방법입니다. Jquery UI 웹 사이트에서 소스를 가져 와서 제약 조건을 추가하도록 수정했습니다.

$(document).ready(function ()
{      
  var dates = $('#StartDate, #EndDate').datepicker({
        minDate: new Date(2008, 11, 1), 
        maxDate: "+0D",
        dateFormat: "dd M yy",
        changeMonth: true,
        changeYear: true,
        onSelect: function (selectedDate)
        {
            var option = this.id == "StartDate" ? "minDate" : "maxDate",
                instance = $(this).data("datepicker"),
                date = $.datepicker.parseDate(
                    instance.settings.dateFormat ||
                    $.datepicker._defaults.dateFormat,
                    selectedDate, instance.settings);
            var edate;
            var otherOption;
            var d;
            if (option == "minDate")
            {
                otherOption = "maxDate";
                d = date.getDate() + 7;
            }
            else if (option == "maxDate")
            {
                otherOption = "minDate";
                d = date.getDate() - 7;
            }

            var m = date.getMonth();
            var y = date.getFullYear();
            edate = new Date(y, m, d);

            dates.not(this).datepicker("option", option, date);
            dates.not(this).datepicker("option", otherOption, edate);
        }
    });
});

초기 아이디어 : http://jqueryui.com/demos/datepicker/#date-range

참고 : 날짜를 재설정 / 지울 수있는 옵션도 필요합니다 (예 : 사용자가 '시작 날짜'를 선택하면 '종료 날짜'가 제한됩니다. 사용자가 이제 '종료 날짜'를 선택한 경우 '시작 날짜'를 선택한 후) ', 시작 날짜도 제한됩니다. 사용자가 지금 다른 "시작"날짜를 선택할 수 있도록 명확한 옵션이 있어야합니다.)

참조 URL : https://stackoverflow.com/questions/330737/jquery-datepicker-2-inputs-textboxes-and-restricting-range

반응형