6

任何人都可以向我推荐一个具有最小和最大日期功能的好的 javascript 月份范围选择器。

我用谷歌搜索了它,但找不到一个好的。我已经看到了一个 JQuery UI 日期选择器修改。但是当我通过最大和最小日期时,它无法正常工作,并且显示错误的年份和月份。

下面是我尝试过的代码。

<script type="text/javascript">
$(document).ready(function() {  
    $( "#fromMonth, #toMonth" ).datepicker({    
            changeMonth: true,
            changeYear: true,
            showButtonPanel: false,
            dateFormat: 'M yy',
                            minDate:new Date(2010, 1 - 1, 1),
                maxDate:new Date(2012, 4 - 1, 1),   
            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));
                $(this).datepicker('refresh');
            },
            beforeShow : function(input, inst) {
                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', 'monthNames'));
                    $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
                    $(this).datepicker('setDate', new Date(year, month, 1));    
                }
                var other = this.id == "fromMonth" ? "#toMonth" : "#fromMonth";
                var option = this.id == "fromMonth" ? "maxDate" : "minDate";        
                if ((selectedDate = $(other).val()).length > 0) {
                    year = selectedDate.substring(selectedDate.length-4, selectedDate.length);
                    month = jQuery.inArray(selectedDate.substring(0, selectedDate.length-5), $(this).datepicker('option', 'monthNames'));
                    $(this).datepicker( "option", option, new Date(year, month, 1));
                }
            }
        });
        $("#btnShow").click(function(){ 
        if ($("#fromMonth").val().length == 0 || $("#toMonth").val().length == 0){
            alert('All fields are required');
        }
        else{
            alert('Selected Month Range :'+ $("#from").val() + ' to ' + $("#to").val());
            }
        })

});

</script>
<style type="text/css">
.ui-datepicker-calendar {display: none;}
</style>

谁能告诉我上面的代码有什么问题或提出一个好的解决方案?

4

2 回答 2

3

我建议DateRangePicker,一个轻量级的月份范围选择器,非常容易定制

用例

$('input').rangePicker({ minDate:[2,2009], maxDate:[10,2013] })
    // subscribe to the "done" event after a date was selected
    .on('datePicker.done', function(e, result){
        console.log(result);
    });

可用设置:

{
    RTL : false,
    closeOnSelect : true,
    presets : [{
            buttonText  : '1 month',
            displayText : 'one month',
            value       : '1m'
        },{
            buttonText  : '3 months',
            displayText : 'three months',
            value       : '3m'
        },{
            buttonText  : '6 months',
            displayText : 'six months',
            value       : '6m'
        },{
            buttonText  : '12 months',
            displayText : 'twelve months',
            value       : '12m'
    }],
    months  : ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'],
    minDate : [5,2006],
    maxDate : [8,2013],
    setDate : null
}
于 2015-09-13T20:56:35.143 回答
2

我发现的新组件:https ://codepen.io/nathanfiscus/pen/qELYjG

<div id="sla-data-range" class="mrp-container nav navbar-nav">
  <span class="mrp-icon"><i class="fa fa-calendar"></i></span>
  <div class="mrp-monthdisplay">
    <span class="mrp-lowerMonth">Jul 2014</span>
    <span class="mrp-to"> to </span>
    <span class="mrp-upperMonth">Aug 2014</span>
  </div>
<input type="hidden" value="201407" id="mrp-lowerDate" />
<input type="hidden" value="201408" id="mrp-upperDate" />

    var MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

$(function () {
  startMonth = 7;
  startYear = 2014
  endMonth = 8;
  endYear = 2015;
  fiscalMonth = 7;
  if(startMonth < 10)
    startDate = parseInt("" + startYear + '0' + startMonth + "");
  else
    startDate = parseInt("" + startYear  + startMonth + "");
  if(endMonth < 10)
    endDate = parseInt("" + endYear + '0' + endMonth + "");
  else
    endDate = parseInt("" + endYear + endMonth + "");

  content = '<div class="row mpr-calendarholder">';
  calendarCount = endYear - startYear;
  if(calendarCount == 0)
    calendarCount++;
  var d = new Date();
  for(y = 0; y < 2; y++){
        content += '<div class="col-xs-6" ><div class="mpr-calendar row" id="mpr-calendar-' + (y+1) + '">'
                         + '<h5 class="col-xs-12"><i class="mpr-yeardown fa fa-chevron-circle-left"></i><span>' + (startYear + y).toString() + '</span><i class="mpr-yearup fa fa-chevron-circle-right"></i></h5><div class="mpr-monthsContainer"><div class="mpr-MonthsWrapper">';
    for(m=0; m < 12; m++){
      var monthval;
      if((m+1) < 10)
        monthval = "0" + (m+1);
      else
        monthval = "" + (m+1);
            content += '<span data-month="' + monthval  + '" class="col-xs-3 mpr-month">' + MONTHS[m] + '</span>';
    }
    content += '</div></div></div></div>';
  }
  content += '<div class="col-xs-1"> <h5 class="mpr-quickset">Quick Set</h5>';
  content += '<button class="btn btn-info mpr-fiscal-ytd">Fiscal YTD</button>';
  content += '<button class="btn btn-info mpr-ytd">YTD</button>';
  content += '<button class="btn btn-info mpr-prev-fiscal">Previous FY</button>';
  content += '<button class="btn btn-info mpr-prev-year">Previous Year</button>';
  content += '</div>';
  content += '</div>';

  $(document).on('click','.mpr-month',function(e){
    e.stopPropagation();
        $month = $(this);
        var monthnum = $month.data('month');
        var year = $month.parents('.mpr-calendar').children('h5').children('span').html();
        if($month.parents('#mpr-calendar-1').size() > 0){
          //Start Date
          startDate = parseInt("" + year + monthnum);
          if(startDate > endDate){

            if(year != parseInt(endDate/100))
              $('.mpr-calendar:last h5 span').html(year);
               endDate = startDate;
          }
        }else{
          //End Date
          endDate = parseInt("" + year + monthnum);
          if(startDate > endDate){
            if(year != parseInt(startDate/100))
              $('.mpr-calendar:first h5 span').html(year);
            startDate = endDate;
          }
        }

        paintMonths();
  });


  $(document).on('click','.mpr-yearup',function(e){
        e.stopPropagation();
        var year = parseInt($(this).prev().html());
        year++;
        $(this).prev().html(""+year);
        $(this).parents('.mpr-calendar').find('.mpr-MonthsWrapper').fadeOut(175,function(){
        paintMonths();
        $(this).parents('.mpr-calendar').find('.mpr-MonthsWrapper').fadeIn(175);
      });
  });

  $(document).on('click','.mpr-yeardown',function(e){
        e.stopPropagation();
        var year = parseInt($(this).next().html());
        year--;
        $(this).next().html(""+year);
        //paintMonths();
      $(this).parents('.mpr-calendar').find('.mpr-MonthsWrapper').fadeOut(175,function(){
        paintMonths();
        $(this).parents('.mpr-calendar').find('.mpr-MonthsWrapper').fadeIn(175);
      });
  });

  $(document).on('click','.mpr-ytd', function(e){
    e.stopPropagation();
    var d = new Date();
    startDate = parseInt(d.getFullYear() + "01");
    var month = d.getMonth() + 1;
    if(month < 9)
      month = "0" + month;
    endDate = parseInt("" + d.getFullYear() + month);
    $('.mpr-calendar').each(function(){
      var $cal = $(this);
      var year = $('h5 span',$cal).html(d.getFullYear());
    });
    $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeOut(175,function(){
        paintMonths();
        $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeIn(175);
    });
  });

  $(document).on('click','.mpr-prev-year', function(e){
    e.stopPropagation();
    var d = new Date();
    var year = d.getFullYear()-1;
    startDate = parseInt(year + "01");
    endDate = parseInt(year + "12");
    $('.mpr-calendar').each(function(){
      var $cal = $(this);
      $('h5 span',$cal).html(year);
    });
    $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeOut(175,function(){
        paintMonths();
        $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeIn(175);
    });
  });

  $(document).on('click','.mpr-fiscal-ytd', function(e){
    e.stopPropagation();
    var d = new Date();
    var year;
    if((d.getMonth()+1) < fiscalMonth)
      year = d.getFullYear() - 1;
    else
      year = d.getFullYear();
    if(fiscalMonth < 10)
      fm = "0" + fiscalMonth;
    else
      fm = fiscalMonth;
    if(d.getMonth()+1 < 10)
      cm = "0" + (d.getMonth()+1);
    else
      cm = (d.getMonth()+1);
    startDate = parseInt("" + year + fm);
    endDate = parseInt("" + d.getFullYear() + cm);
    $('.mpr-calendar').each(function(i){
      var $cal = $(this);
      if(i == 0)
        $('h5 span',$cal).html(year);
      else
        $('h5 span',$cal).html(d.getFullYear());
    });
    $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeOut(175,function(){
        paintMonths();
        $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeIn(175);
    });
  });

  $(document).on('click','.mpr-prev-fiscal', function(){
    var d = new Date();
    var year;
    if((d.getMonth()+1) < fiscalMonth)
      year = d.getFullYear() - 2;
    else
      year = d.getFullYear() - 1;
    if(fiscalMonth < 10)
      fm = "0" + fiscalMonth;
    else
      fm = fiscalMonth;
    if(fiscalMonth -1 < 10)
      efm = "0" + (fiscalMonth-1);
    else
      efm = (fiscalMonth-1);
    startDate = parseInt("" + year + fm);
    endDate = parseInt("" + (d.getFullYear() - 1) + efm);
    $('.mpr-calendar').each(function(i){
      var $cal = $(this);
      if(i == 0)
        $('h5 span',$cal).html(year);
      else
        $('h5 span',$cal).html(d.getFullYear()-1);
    });
    $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeOut(175,function(){
        paintMonths();
        $('.mpr-calendar').find('.mpr-MonthsWrapper').fadeIn(175);
    });
  });

  var mprVisible = false;
  var mprpopover = $('.mrp-container').popover({
    container: "body",
    placement: "bottom",
    html: true,
    content: content
  }).on('show.bs.popover', function () {
    $('.popover').remove();
    var waiter = setInterval(function(){
      if($('.popover').size() > 0){
        clearInterval(waiter);
        setViewToCurrentYears();
            paintMonths();
      }
    },50);
  }).on('shown.bs.popover', function(){
    mprVisible = true;
  }).on('hidden.bs.popover', function(){
    mprVisible = false;
  }); 

  $(document).on('click','.mpr-calendarholder',function(e){
    e.preventDefault();
    e.stopPropagation();
  });
  $(document).on("click",".mrp-container",function(e){
    if(mprVisible){
      e.preventDefault();
        e.stopPropagation();
      mprVisible = false;
    }
  });
  $(document).on("click",function(e){
    if(mprVisible){
        $('.mpr-calendarholder').parents('.popover').fadeOut(200,function(){
        $('.mpr-calendarholder').parents('.popover').remove();
        $('.mrp-container').trigger('click');
      });
      mprVisible = false;
    }
  });
});

function setViewToCurrentYears(){
    var startyear = parseInt(startDate / 100);
    var endyear = parseInt(endDate / 100);
    $('.mpr-calendar h5 span').eq(0).html(startyear);
    $('.mpr-calendar h5 span').eq(1).html(endyear);
}

function paintMonths(){
    $('.mpr-calendar').each(function(){
      var $cal = $(this);
      var year = $('h5 span',$cal).html();
      $('.mpr-month',$cal).each(function(i){
        if((i+1) > 9)
          cDate = parseInt("" + year + (i+1));
        else
          cDate = parseInt("" + year+ '0' + (i+1));
        if(cDate >= startDate && cDate <= endDate){
            $(this).addClass('mpr-selected');
        }else{
          $(this).removeClass('mpr-selected');
        }
      });
    });
  $('.mpr-calendar .mpr-month').css("background","");
    //Write Text
    var startyear = parseInt(startDate / 100);
    var startmonth = parseInt(safeRound((startDate / 100 - startyear)) * 100);
    var endyear = parseInt(endDate / 100);
    var endmonth = parseInt(safeRound((endDate / 100 - endyear)) * 100);
    $('.mrp-monthdisplay .mrp-lowerMonth').html(MONTHS[startmonth - 1] + " " + startyear);
    $('.mrp-monthdisplay .mrp-upperMonth').html(MONTHS[endmonth - 1] + " " + endyear);
    $('.mpr-lowerDate').val(startDate);
    $('.mpr-upperDate').val(endDate);
    if(startyear == parseInt($('.mpr-calendar:first h5 span').html()))
        $('.mpr-calendar:first .mpr-selected:first').css("background","#40667A");
    if(endyear == parseInt($('.mpr-calendar:last h5 span').html()))
      $('.mpr-calendar:last .mpr-selected:last').css("background","#40667A");
  }

  function safeRound(val){
    return Math.round(((val)+ 0.00001) * 100) / 100;
  }

在此处输入图像描述

于 2018-02-14T09:46:55.073 回答