Saturday, February 2, 2019

Restrict users to select specific days in date picker via JavaScript

For this post I have two date picker item and I want to restrict users to select dates just between “From Date“ and seven days after that.



Add below JavaScript function in “Function and Global Variable Declaration” of page :

function addDays(date, inx) {
    var d = new Date(date);
    d.setDate(d.getDate() + inx);  
    return d;
}

Then add below javascript code in “Execute when Page Loads” :

$('#P29_FROM_DATE').datepicker('option', 'onSelect', function(dateTxt, inst) {
    var currentDay = new Date(inst['selectedYear'], inst['selectedMonth'], inst['selectedDay']);
    $('#P29_TO_DATE').datepicker('option', 'minDate', addDays(currentDay, 0));
    $('#P29_TO_DATE').datepicker('option', 'maxDate', addDays(currentDay, 7));
});

Tip: If you are using Persian Date Picker plug-in, use below javascript code instead of previous code in “Execute when Page Loads”:


$('#P29_FROM_DATE').datepicker('option', 'onSelect', function(dateTxt, inst) {
    var
currentDay= new JalaliDate(inst['selectedYear'], inst['selectedMonth'], inst['selectedDay']).getGregorianDate();
    $('#P29_TO_DATE').datepicker('option', 'minDate', addDays(
currentDay, 0));
    $('#P29_TO_DATE').datepicker('option', 'maxDate', addDays(
currentDay, 7));
}); 




No comments:

Post a Comment