Daterangepicker min date - daterangepicker

I have module that has delivery date and I used the daterangepicker for my delivery date. I want to set my daterangepicker current year until 10 yrs from now
JS
$('#date_needed').append(''
+'<input type="text" class="form-control dates_edit" name="date_needed" />'
)
$('.dates_edit').daterangepicker({
yearRange: '2019:c+10',
singleDatePicker: true,
minDate: new Date('2019:c+10'),
showDropdowns: true
});
Question: How can I make my min date for my date_needed daterangepicker?

minDate: new Date(new Date().setFullYear(new Date().getFullYear() + 10))

Thanks to #RaviTeja V my problem is now solved by doing this:
$('.dates_edit').daterangepicker({
yearRange: '2019:c+10',
singleDatePicker: true,
minDate : new Date(), maxDate: new Date(new Date().setFullYear(new Date().getFullYear() + 10)),
showDropdowns: true
});
But can someone explain to me,why my code below didn't work?
$('.dates_edit').daterangepicker({
yearRange: '2019:c+10',
singleDatePicker: true,
minDate: new Date(new Date().setFullYear(new Date().getFullYear())),
maxDate: new Date(new Date().setFullYear(new Date().getFullYear() +10)),
showDropdowns: true
});
Is there any difference between the two?

Related

Validate a date on liferay

What is the best way to validate a date input which can be changed with text? I've tried with aui:validator with no success, when I click on the datepicker, the onSelect doesn't update the value and my custom validation recieves the old value from the datepicker.
<aui:input type="text" name="creationDate" id="creationDate" class="datefield">
<aui:validator name="required"/>
<aui:validator name="custom" errorMessage="Default error message">
function (val, fieldNode, ruleValue) {
var date = new Date(val);
var today = new Date();
return (date < today);
}
}
</aui:validator>
</aui:input>
<script type="text/javascript">
$(document).ready(function(){
$("#creationDate").datepicker("option", "minDate", 0);
}
</script>
Try this:
$("#creationDate").datepicker(
{
minDate: 0,
onClose: function() {
$(this).focus().blur();
}
}
);

Reloading of data in JQgrid on button click is not working

I have successfully loaded data in my grid. I have enabled cell edit and on clicking a cell it will be in edit mode and multiple cells can be edited. The edited data will be stored later on clicking a custom update button. On clicking another custom button a new row will be added to the grid and that also will be saved on clicking the update button previously mentioned.
Now the problem is when I am trying to reset the edited values(ie. the edited cell values and the new row added before saving) using "reload" functionality nothing happens in the grid.It remains as same with the edited values and the empty new row...
My code is here
$scope.init = function() {
var grid = $("#list");
var lastSel, dataSel, dataLen;
var colD, colM, colN, userdata;
jQuery.ajax({
async: false,
type: "GET",
url:"getData.htm",
data: "",
dataType: "json",
success: function(result){
colD = result.colData,
colM = result.colModel,
colN = result.colNames,
userdata = colD.userdata;
jQuery("#list").jqGrid({
datatype: 'local',
data: colD.rootVar,
colModel:colM,
sortorder: 'asc',
viewrecords: true,
resizable: true,
gridview: true,
altRows: true,
cellEdit:true,
footerrow: true,
scrollbar: true,
overflow: scroll,
scrollrows: true,
loadonce:true,
autowidth: true,
shrinkToFit: false,
editurl: 'clientArray',
cellsubmit: 'clientArray',
afterEditCell: function (id,name,val,iRow,iCol){
},
afterSaveCell : function(rowid,name,val,iRow,iCol) {
var updtd = jQuery("#list").jqGrid('getCol', name, false, 'sum');
var objs = [];
objs[name] = updtd;
jQuery("#list").jqGrid('footerData','set',objs);
},
loadComplete: function(data){
jQuery("#list").jqGrid('footerData','set',{'Employer':'Max Guest Count:'});
var colnames = jQuery("#list").jqGrid ('getGridParam', 'colModel');
dataLen = colnames.length;
dataSel = colnames[3]['name'];
for (var i = 3; i < colnames.length; i++){
var tot = jQuery("#list").jqGrid('getCol', colnames[i]['name'], false, 'sum');
var ob = [];
ob[colnames[i]['name']] = tot;
jQuery("#list").jqGrid('footerData','set',ob);
}
var ids = grid.getDataIDs();
for (var i = 0; i < ids.length; i++) {
grid.setRowData ( ids[i], false, {height: 25} );
}
jQuery ("table.ui-jqgrid-htable", jQuery("#list")).css ("height", 30);
},
gridComplete: function () {
jQuery("#list").jqGrid('setColProp','id',{width:20});
jQuery("#list").jqGrid('setColProp','Employer',{width:80});
jQuery("#list").jqGrid('setColProp','Sponsor',{width:80});
var tabs = $("#tabs");
var width = tabs.width();
jQuery("#list").jqGrid('setGridWidth', width - 80, true);
jQuery("#list").jqGrid('setGridHeight', 270);
},
});
},
});
jQuery("#list").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'id', numberOfColumns: 1, titleText: ''},
{startColumnName: 'Employer', numberOfColumns: 2, titleText: ''},
{startColumnName: dataSel, numberOfColumns: dataLen, titleText: '<Strong><font color="white">Here Comes</font></Strong>'}
]
});
$("#addtn").click(function(){
var newRowData = {"Id":"","Employer":"","Sponsor":"",col1:"",col2:"",col3:"",col4:"",col5:"",col6:"",col7:"",col8:"",col9:"",col10:"",col11:"",col12:"",col13:"",col14:"",col15:"",col16:"",col17:"",col18:"",col19:"",col20:""};
jQuery("#list").addRowData(0,newRowData,"first",1);
jQuery("#list").editRow(0,true);
});
$("#rstbtn").click(function(){
$("#list").jqGrid('setGridParam',{datatype:'json', page:1, current:true}).trigger('reloadGrid')
});
};
I will really appreciate if someone can advice on this..
Probably because of this line: loadonce:true, in jqgrid definition. Set it as false and try again.
And for reloading, try this code:
$( '#list' ).trigger( 'reloadGrid', [{ page: 1}] );
Below code worked for me, to load updated data from the array.
$('#grid').jqGrid('clearGridData');
$("#grid").jqGrid('setGridParam',{data: DataArr, datatype:'local'}).trigger('reloadGrid');

text input datepicker enddate after startdate validation

I have 2 input boxes, startdate and enddate. I am trying to force the user to select a date in the 2nd input box that is after the date in the first input box. This will be validated on ajax save.
Everything including the isvalid works great in ie but does not work in FF or opera.
In FF and opera no matter what the date before or after start date, it just keeps displaying the isValid: "Must be after start date" message and not validating.
Does anybody have any ideas why, or a solution using the datepickers so it modifies the minDate on the 2nd datepicker.
Here are the buttons for the ajax modal:
buttons: {
'Save': function() {
if($("#new_request_form").valid()){
// do stuff if form validates
submitFormWithAjax($("#new_request_form"));
$(this).dialog('close');
} else {
// do stuff if form does not validate
}
},
'Cancel': function() {$(this).dialog('close');}
},
Here is the date check to make sure the enddate is after the startdate:
jQuery.validator.addMethod("isValid", function (value, element) {
var startDate = $('#startdate').val();
var finDate = $('#enddate').val();
return Date.parse(startDate) < Date.parse(finDate);
}, "* End date must be after start date");
$("#new_request_form").validate({
rules: {
days: "required",
hours: {
required: true,
number: true,
digits: false
},
startdate: "required",
enddate: {
required: true,
isValid: true
}
},
messages:{
days: "Required",
hours: {
required: "Required",
number: "Numbers Only"
},
startdate: "Required",
enddate: {
required: "Required",
isValid: "Must be after start date"
}
}
});
var $ac_start_date = '<?php echo $ac_end_date ?>',
$ac_start_date_flip = '<?php echo $ac_end_date_flip ?>',
$ac_start_parsed = Date.parse($ac_start_date),
_today = new Date().getTime();
// For Opera and older winXP IE n such
if (isNaN($ac_start_parsed)) {
$ac_start_parsed = Date.parse($ac_start_date_flip);
}
var _aDayinMS = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
var difference_ms = Math.abs($ac_start_parsed - _today);
// Convert back to days and return
var DAY_DIFFERENCE = Math.round(difference_ms/_aDayinMS);
// do initialization here
$("#startdate").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
yearRange: '0:+100',
minDate: '+1d',
maxDate: '+' + (DAY_DIFFERENCE + 1) + 'd'
});
// do initialization here
$("#enddate").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
yearRange: '0:+100',
minDate: '+1d',
maxDate: '+' + (DAY_DIFFERENCE + 1) + 'd'
});
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
}
});
return false;
}

Backbone.js Model, adding setInterval correctly

I'm creating a simple Backbone app for learning purposes. I'm just creating a time and date display. The display has to update at least every minute. I'm using "Time" for the model and "TimeView" for the View. My first question is sort-of philosophical, which holds the setInterval, the Model or the View? I think that the Model should self-update but I couldn't get the code to work. It looks like it's updating the model but the binding of model.update() to the view.render() function doesn't work.
In the code below, I switched the setInterval to the View and commented out my other attempt. Even though this works, (and maybe the View should control the updating of the model) but this.model.bind( 'update', this.render ) doesn't work and I have to initiate the render seperately which feels wrong.
var Time = Backbone.Model.extend({
initialize: function(){
_.bindAll( this, 'update', 'startLoop', 'stopLoop' );
//this.startLoop();
this.update();
},
startLoop: function(){
this.update();
this.interval = window.setInterval(_.bind(this.update, this), 10000);
},
stopLoop: function(){
this.interval = window.clearInterval( this.interval );
},
update: function(){
var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
var date = new Date();
var tHour = date.getHours();
if( tHour < 12 ){ if( tHour == 0 ) tHour = 12 } else { tHour = tHour-12 };
tHour = tHour.toString();
var tMin = date.getMinutes();
tMin = ( tMin < 10 ) ? '0' + tMin.toString() : tMin.toString();
this.set({
hour : tHour,
ampm : ( date.getHours() < 12 ) ? "am" : "pm",
minute : tMin,
day : days[ date.getDay() ],
month : months[ date.getMonth() ],
date : date.getDate(),
year : date.getFullYear()
});
}
});
var TimeView = Backbone.View.extend({
el: '#time-date-display',
interval: 0,
template: $( '#tpl-time-date' ).html(),
initialize: function(){
_.bindAll( this, 'render' );
this.model = new Time();
this.render();
//this.model.bind( 'update', this.render );
this.interval = window.setInterval( _.bind( function(){ this.model.update(); this.render();}, this), 10000 );
},
render: function(){
//alert( 'TimeView.render()' );
$( this.el ).html(
_.template( this.template, this.model.toJSON())
);
}
});
$( 'body' ).append( _.template( $( '#tpl-time-weather-display' ).html()));
var tv=new TimeView();
You are binding to the update event on the model, but that event will never be triggered. Calling update on the model isn’t the same as an update event being generated. Instead, bind to the model’s change event, then the view will be updated.
Regarding the philosophical question, I’d choose the model to be updating with the time, too, but this example is so contrived it’s almost arbitrary.

datepicker JQuery Validations and Format

I am using the following for datepicker in Jquery to format the date display in dd/mm/yy format and also I want the user not to select future date.Only one thing is working at a time.
<script type="text/javascript" language ="javascript" >
$(function () {
var date = new Date();
var currentDate = date.getDate();
var currentMonth = date.getMonth();
var currentYear = date.getFullYear();
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
$(".datepicker").datepicker({ maxDate: new Date(currentYear, currentMonth, currentDate) });
});
</script>
How do make, both the dateformat and disable the future dates to work simultaneously. I am missing single bit, I don't know how to club this two validations or requirements togather.
Any answers Please?
Thank you.
I had a similar requirement for my code with a hire date. Here's how I did it:
$('#hireDate').datepicker({
dateFormat: 'dd/mm/yy',
maxDate: new Date(currentYear, currentMonth, currentDay)
});
The user can still enter a future date manually and weasel around your date picker. We had this problem on a production system.
If you want to additionally validate the date using the validation plugin, try this:
/**
* Requires Datepicker and Validator
*
* Params:
* 0...dateformat. see datepicker
* 1...date. Value "0" is "today"
* 2...(optional). date to display. will be automatically filled if 0 and 1 are set.
* usage:
* myfield: { maxDate: ['m/d/yy', 0] }
*/
jQuery.validator.addMethod("maxDate",
function(value, element, params) {
if (!params[0])
throw 'params missing dateFormat';
if (typeof(params[1]) == 'undefined' )
throw 'params missing maxDate';
var dateFormat = params[0];
var maxDate = params[1];
if (maxDate == 0) {
maxDate = new Date();
maxDate.setHours(0); // make it 00:00:0
maxDate.setMinutes(0);
maxDate.setSeconds(0);
maxDate.setMilliseconds(0);
}
if (typeof(params[2]) == 'undefined' )
params[2] = $.datepicker.formatDate(dateFormat, maxDate);
try {
var valueAsDate = $.datepicker.parseDate( dateFormat, value )
return (valueAsDate < maxDate);
} catch (x) {
return false;
}
},'Must be greater than {2}.');
$("#myform").validate({
rules: {
datepicker : {
maxDate ['m/d/yy', 0]
}
}
});
HTML:
<input name="datepicker" class="datepicker" type="text"/>

Resources