Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript month range picker

Tags:

javascript

can anyone suggest me a good javascript month range picker with min and max date functionality.

I have googled it and not able to find a good one. I have seen a JQuery UI datepicker modification. But when i am passing max and min dates it is not working properly and it showing wrong years and months.

below is the code which i have tried.

<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>

can anyone tell me what is wrong in above code or suggest a good solution?

like image 644
codlib Avatar asked May 18 '12 09:05

codlib


2 Answers

I suggest DateRangePicker, a lightweight month range picker which is very easy to customize

Usecase

$('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);
    });

Available Settings:

{
    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
}
like image 134
vsync Avatar answered Oct 20 '22 00:10

vsync


new component I found : 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;
  }

enter image description here

like image 28
4givN Avatar answered Oct 19 '22 22:10

4givN