Showing posts with label jquery-ui-datepicker. Show all posts
Showing posts with label jquery-ui-datepicker. Show all posts

Thursday, April 27, 2017

Jquery Datepicker select multiple date ranges in one calender

Leave a Comment

My requirement is to allow user to select multiple date ranges in a single calendar, also previous date selections should not be allowed to change. How is this possible? Below is the code and link to fiddle

HTML

<p>from</p> <input type="text" class="spromotion-input-inbody spromotion-input-datepick" id="sproid-bookingcondition-datefrom"> <p>to</p> <input type="text" class="spromotion-input-inbody spromotion-input-datepick" id="sproid-bookingcondition-dateto"> 

SCRIPT

$( function() {     var dateFormat = "mm/dd/yy",       from = $( "#sproid-bookingcondition-datefrom" )         .datepicker({           defaultDate: "+1w",           changeMonth: true,           numberOfMonths: 1         })         .on( "change", function() {           to.datepicker( "option", "minDate", getDate( this ) );         }),       to = $( "#sproid-bookingcondition-dateto" ).datepicker({         defaultDate: "+1w",         changeMonth: true,         numberOfMonths: 1       })       .on( "change", function() {         from.datepicker( "option", "maxDate", getDate( this ) );       });      function getDate( element ) {       var date;       try {         date = $.datepicker.parseDate( dateFormat, element.value );       } catch( error ) {         date = null;       }        return date;     }   } ); 

5 Answers

Answers 1

Please check this might solve your issue.

$(function() {      $('input[name="daterange"]').daterangepicker();      $('input[name="daterange"]').change(function(){        $(this).val();        console.log($(this).val());      });  });
<html>  <head>  <!-- Include Required Prerequisites -->  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>  <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>  <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" />     <!-- Include Date Range Picker -->  <script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>  <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />  </head>  <body>    <input class="pull-right" type="text" name="daterange" value="01/15/2020 - 02/15/2010">  </body>  </html>

Answers 2

I think this Multi datepicker will help you to solve your problem.

$('#mdp-demo').multiDatesPicker();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <link href="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.css" rel="stylesheet"/>  <link href="https://code.jquery.com/ui/1.12.1/themes/pepper-grinder/jquery-ui.css" rel="stylesheet"/>  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>  <script src="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.js"></script>  <div id="mdp-demo"></div>

Answers 3

Unfortunately this is not something the datepicker plugin is able to do out of the box. You will need some custom JavaScript to enable this.

I found a way which gets close to what you want using the onSelect and beforeShowDay events. It maintains its own array of selected dates, so unfortunately doesn't integrate with a textbox showing the current date, etc. I'm just using it as an inline control, and I can then query the array for the currently selected dates.

The only thing you would need to alter about this code is grouping every two dates into ranges, but there are multiple ways to do that depending on your desired UX. Personally, I would just group every two dates as a range in the order the user selects. Then if they remove a date from any range, the entire range is removed (that is not coded here, you will need to add that).

Here is my code:

<script> // Maintain array of dates var dates = new Array();  function addDate(date) {     if (jQuery.inArray(date, dates) < 0)          dates.push(date); }  function removeDate(index) {     dates.splice(index, 1); }  // Adds a date if we don't have it yet, else remove it function addOrRemoveDate(date) {     var index = jQuery.inArray(date, dates);     if (index >= 0)          removeDate(index);     else          addDate(date);     }  // Takes a 1-digit number and inserts a zero before it function padNumber(number) { var ret = new String(number); if (ret.length == 1)      ret = "0" + ret;     return ret; }  jQuery(function () {     jQuery("#datepicker").datepicker({         onSelect: function (dateText, inst) {             addOrRemoveDate(dateText);         },         beforeShowDay: function (date) {             var year = date.getFullYear();             // months and days are inserted into the array in the form, e.g "01/01/2009", but here the format is "1/1/2009"             var month = padNumber(date.getMonth() + 1);             var day = padNumber(date.getDate());             // This depends on the datepicker's date format             var dateString = month + "/" + day + "/" + year;              var gotDate = jQuery.inArray(dateString, dates);             if (gotDate >= 0) {                 // Enable date so it can be deselected. Set style to be highlighted                 return [true, "ui-state-highlight"];             }             // Dates not in the array are left enabled, but with no extra style             return [true, ""];         }     }); }); </script> 

And here is a fiddle: http://jsfiddle.net/gydL0epa/

Answers 4

As others already suggested, MultiDatesPicker comes close to what your need. It already allows single range selection, so you could fork that plugin and edit/improve it to allow multiple ranges selection.

A quick and dirty solution would be to comment out the line where the array of selected dates gets reset.

Answers 5

try this

<!DOCTYPE html> <html> <head>     <title></title>     <meta charset="utf-8" />     <script src="Scripts/jquery-1.11.1.js"></script>     <script src="Scripts/jquery-ui-1.11.1.js"></script>     <script src="Scripts/jquery-ui.multidatespicker.js"></script>     <link href="css/jquery-ui.css" rel="stylesheet" />     <link href="css/jquery-ui.structure.css" rel="stylesheet" />     <link href="css/jquery-ui.theme.css" rel="stylesheet" />     <link href="css/pepper-ginder-custom.css" rel="stylesheet" />     <link href="css/prettify.css" rel="stylesheet" /> </head>  <body>     <input type="text" id="fromDate" />     <script>         $(function () {             $('#fromDate').multiDatesPicker();         });     </script> </body> </html> 

you can download the js file from the link https://sourceforge.net/projects/multidatespickr/

Read More

Saturday, March 12, 2016

Display additional text alongside dates in jQuery UI datepicker

Leave a Comment

I am using jQuery UI datepicker and I want to display additional text inside date cells next to the date. This is the desired behavior:

jQuery UI datepicker with custom text inside cells

Unfortunately, manipulating date cells using .text() and .html() functions breaks the datepicker functionality. See following demo and try to use the datepicker. Notice that when you select a date (i) the custom text is gone (ii) changing months destroys the calendar and lands you on "undefined NaN" month:

https://jsfiddle.net/salman/aLdx4L0y/

Is there a solution?

3 Answers

Answers 1

Well, you can monkey-patch jQuery UI and risk breaking the code with newer versions or you can use documented callbacks to add custom data-* attributes to datepicker and display them using CSS pseudo elements:

$(function() {    $("#datepicker").datepicker({      beforeShow: addCustomInformation,      //---^----------- if closed by default (when you're using <input>)      beforeShowDay: function(date) {        return [true, date.getDay() === 5 || date.getDay() === 6 ? "weekend" : "weekday"];      },      onChangeMonthYear: addCustomInformation,      onSelect: addCustomInformation    });    addCustomInformation(); // if open by default (when you're using <div>)  });    function addCustomInformation() {    setTimeout(function() {      $(".ui-datepicker-calendar td").filter(function() {        var date = $(this).text();        return /\d/.test(date);      }).find("a").attr('data-custom', 110); // Add custom data here    }, 0)  }
.ui-datepicker .weekend .ui-state-default {    background: #FEA;  }  .ui-datepicker-calendar td a[data-custom] {    position: relative;    padding-bottom: 10px;  }  .ui-datepicker-calendar td a[data-custom]::after {    /*STYLE THE CUSTOME DATA HERE*/    content: '$' attr(data-custom);    display: block;    font-size: small;  }
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>  <link href="//code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />  <script src="//code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>  <input id="datepicker">

Here's an updated JSFiddle


Side note: I'm not sure which functionality is broke in your demo, but since this solution is using documented callbacks and CSS, I believe it's less likely to break anything in future than monkey patching

Answers 2

Since the jQuery UI datapicker is pretty monolithic it is difficult to enhance cleanly.

I would go with monkey-patching one of its internal functions, namely _generateHTML.

$.datepicker._generateHTML = (function () {      var realGenerateHtml = $.datepicker._generateHTML;      return function (instance) {          var html = realGenerateHtml.apply(this, arguments), $temp;                    if ( instance.input.is(".datepicker-price") ) {              $temp = $("<table></table>").append(html);              $temp.find(".ui-datepicker-calendar td a").each(function () {                  var yy = $(this).parent().data("year"),                      mm = $(this).parent().data("month"),                      dd = +$(this).text();                    $(this).append("<br><small class='price'>$100</small>");              });              html = $temp[0].innerHTML;          }          return html;      };  })();    $(function() {      $("#datepicker").datepicker();  });
.ui-datepicker .weekend .ui-state-default {    background: #FEA;  }  .price {      color: blue;  }
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>    <div id="datepicker" class="datepicker-price"></div>

Answers 3

Add this code into your JS...

$('#DatePicker').datepicker({ changeMonth: true, changeYear: true, minDate: 0, onSelect: function (date, dp) {     updateDatePickerCells(); }, onChangeMonthYear: function(month, year, dp) {     updateDatePickerCells(); }, beforeShow: function(elem, dp) {      updateDatePickerCells(); }}); updateDatePickerCells(); function updateDatePickerCells(dp) {  setTimeout(function () {      var cellContents = {1: '20', 15: '60', 28: '$99.99'};       $('.ui-datepicker td > *').each(function (idx, elem) {         var value = '$125';//cellContents[idx + 1] || 0;           var className = 'datepicker-content-' + CryptoJS.MD5(value).toString();          if(value == 0)             addCSSRule('.ui-datepicker td a.' + className + ':after {content: "\\a0";}'); //&nbsp;         else             addCSSRule('.ui-datepicker td a.' + className + ':after {content: "' + value + '";}');          $(this).addClass(className);     }); }, 0); } var dynamicCSSRules = []; function addCSSRule(rule) { if ($.inArray(rule, dynamicCSSRules) == -1) {     $('head').append('<style>' + rule + '</style>');     dynamicCSSRules.push(rule); } } 

Demo link... http://jsfiddle.net/pratikgavas/e3uu9/131/

Read More