Link to home
Start Free TrialLog in
Avatar of puneet kumar
puneet kumar

asked on

want 2nd date picker only those date are enable which is more then 1st date picker

Hi my requirement is that i have a 3 date fields which are coming from database . its shows in tabular format in jsp page a checkbox is there in each and every row when i click on checkbox then we can select all 3 dates with date picker select a new date submit . my requirement is when we select 1st date then in when we open the second date picker only those dates are able to select which is more then first date . same as 3rd date picker when click and open 3rd date picker only those dates are able to select which is more then third date.code are below .

my java script code are below -


$(document).ready(function() {

	$(".date").datepicker({dateFormat:'dd/mm/yy'});
	$('.chkValues').on('click', function() {

		//get values of dates
		var array = [];
		var parent = $(this).closest('tr');
	    
	    // Now find all the child <inpu> elements with class "date"
	    var last = 0;
	    var lbl = ['PDate','PaDate','bValue'];
	    $('.date', parent).each(function(i,e) {
	      var dt = new Date(e.value.split("/").reverse().join("-"));
	      console.log(dt.getTime());
	      if (dt.getTime() <= last) {
	    	  alert('Error: ' + lbl[i] + ' date must be greater than ' + lbl[i-1] + ' date');
	      }
	      last = dt.getTime();
	    });
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + $row).each(function() {
			array.push($(this).val());
		});
		$('#btnSubmit').click(function(evt) {
    	evt.preventDefault();
    	var pCode=document.getElementById("pcode").value;
    	var prType=document.getElementById("prtype").value;
    	var prCode=document.getElementById("prcode").value;
    	$.ajax({
            type: "POST",
            url: "Test.jsp",
            data: {array : array , "pCode": pCode , "prType": prType , "prCode": prCode },
            success: function(responseFromServer) {
            	 $.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
                    $('#content').html(resultMessageKey);
                });
    	    	//getClearDateValues();
    		
            },
            error: function() {
                alert("Ajax call Failed to Update Values  into Database");
            }
        }); 
		});

	});

});

Open in new window



my html code is below -


<tr>
<td align="top">
<INPUT type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="row<%=i%>" value="" size="50">
</td>
<td align="left">
<input class="inputText row<%=i%>" type="text" name="mYear" id="mYear"  value="<%=(tableNameList.get(i)==null?"":tableNameList.get(i))%>">
</td>

				<td>
		            <input class="date row<%=i%>" id="payDate<%=i%>" name="pOff" type="text" value="<%=(tableNameList.get(i+1)==null?"":tableNameList.get(i+1))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="paDate<%=i%>" name="pPayment" type="text" value="<%=(tableNameList.get(i+2)==null?"":tableNameList.get(i+2))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="iDate<%=i%>" name="bDate" type="text" value="<%=(tableNameList.get(i+3)==null?"":tableNameList.get(i+3))%>" />
				</td>

</tr>

Open in new window

Avatar of Kimputer
Kimputer

Since your code has some server side additions, I'll just talk in general.


Split each date into it's own id (which you did) and for each, have it have its own event handler for change.

The event handler for the first, should enable the second datepicker, and set the minimum to the date of the first.

Do the same with the second (add handler).


Here's more info on the mindate:  https://api.jqueryui.com/datepicker/#option-minDate

The event is probably  onSelect

Avatar of puneet kumar

ASKER

Hi Kim ,

Please check my below i remove server side addition , please check and tell me above solution in my code it will be very great full for me , Thanx a ton in advance -



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet"
	href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function getData() {
      var result = [];
      $('#phone > tbody > tr').each(function() {
        var $this = $(this);
        if ($this.find('.chkValues').is(':checked')) {
          var row = {};
          row['P'] = $this.find('.dateP').val();
          row['Q'] = $this.find('.dateQ').val();
          row['B'] = $this.find('.dateB').val();
          result.push(row);
        }
      });
  
      return result;
    }
  
$(document).ready(function() {

	$(".date").datepicker({dateFormat:'dd/mm/yy'});
	$('.chkValues').on('click', function() {
		//get values of dates
		var array = [];
		var parent = $(this).closest('tr');
	    
	    // Now find all the child <inpu> elements with class "date"
	    var last = 0;
	    $('.date', parent).each(function(i,e) {
	      var dt = new Date(e.value.split("/").reverse().join("-"));
	      alert(dt);
	      console.log(dt.getTime());
	      if (dt.getTime() <= last) {
	        alert('Error: ' + e.id + ' has an invalid value');
	      }
	      last = dt.getTime();
	    });
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + $row).each(function() {
			array.push($(this).val());
		});
		$('#btnSubmit').click(function(evt) {
    	evt.preventDefault();
    	$.ajax({
            type: "POST",
            url: "Test.jsp",
            data: {array : array},
            success: function(responseFromServer) {
            	 $.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
                    $('#content').html(resultMessageKey);
                });
    	    },
            error: function() {
                alert(" Ajax call Failed to Update Values  into Database ");
            }
        }); 
		});

	});

});
  </script>
  </head>
<body>
	<form action="" method="post">
		<table id="phone" width="100%" name="phone">
			<tr>
				<th>Check/UnCheck</th>
				<th>MYear</th>
				<th>P Date</th>
				<th>Q Date</th>
				<th>B Date</th>
			</tr>
			<%
				for (int i = 0; i < 5; i++) {
			%>
			<tr>
				<td><INPUT type="checkbox" data-row="row<%=i%>" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" value="<%=i%>" size="50"></td>
				<td align="left"><input class="inputText row1" type="text" name="mYear" id="mYear"  value="2020"></td>
				<td><input class="date row<%=i%>"  id="pDate<%=i%>" name="dob" type="text" value="24/01/2019" /></td>
				<td><input class="date row<%=i%>" id="qDate<%=i%>" name="dob" type="text" value="28/01/2019" /></td>
				<td><input class="date row<%=i%>" id="bDate<%=i%>" name="dob" type="text" value="31/01/2019" /></td>
			</tr>
			<%
				}
			%>
		</table>
		<input id="btnSubmit" type="submit" name="submit" value="submit" />
		</p>
	</form>
</body>
</html>

Open in new window

Add this javascript code:


	$( "#pDate1" ).datepicker({ 
	dateFormat:'dd/mm/yy', 
		onSelect: function(d,i){ 
		$('#qDate1').datepicker('destroy'); 
$("#qDate1").datepicker({dateFormat:'dd/mm/yy', minDate: new Date($( "#pDate1" ).datepicker( "getDate" ))}); 
if ($( "#pDate1" ).datepicker( "getDate" ) > $( "#qDate1" ).datepicker( "getDate" )) {  
$( "#qDate1" ).val($.datepicker.formatDate("dd/mm/yy", $( "#pDate1" ).datepicker( "getDate" ))) ; 
} 
     } 
	} ) 
	 

Open in new window


So qdate1 datepicker is not enabled. It is only enabled after selecting pdate1. If you pick a date, qdate1 datepicker will only start from that date. If the date filled in qdate is before what you picked in pdate1, it will be filled in with that date (it makes no sense to have it input earlier).


So all you need is to copy the code again, but jump from pdate1 to qdate1, and qdate1 to bdate1.

You probably have to make the same loop to generate this script.

You may want to add javascript code to make qdate and bdate greyed out when you start out (add code to ENABLE it after selecting pdate)

Hi Kim ,


i have done the  modification but its not working please check below code . and please tell me how to loop it for all three dates pDate , qDate , bDate and its in tabular format and there id is like pDate1 , qDate1 and bDate1 and pDate2 , qDate2 and bDate2 like this only how i can manage these things. frankly telling you i m new in java script i don't have much knowledge for the same please tell me in my code if possible . thanx a ton for you guys great support .


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet"
	href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function() {

	$( "#pDate1" ).datepicker({ 
	dateFormat:'dd/mm/yy', 
		onSelect: function(d,i){ 
		$('#qDate1').datepicker('destroy'); 
			$("#qDate1").datepicker({dateFormat:'dd/mm/yy', minDate: new Date($( "#pDate1" ).datepicker( "getDate" ))}); 
				if ($( "#pDate1" ).datepicker( "getDate" ) > $( "#qDate1" ).datepicker( "getDate" )) {  
					$( "#qDate1" ).val($.datepicker.formatDate("dd/mm/yy", $( "#pDate1" ).datepicker( "getDate" ))) ; 
				} 
			} 
		} ) 
	
	
	$('.chkValues').on('click', function() {
		//get values of dates
		var array = [];
		var parent = $(this).closest('tr');
	    
	    // Now find all the child <input> elements with class "date"
	    var last = 0;
	    $('.date', parent).each(function(i,e) {
	      var dt = new Date(e.value.split("/").reverse().join("-"));
	      alert(dt);
	      console.log(dt.getTime());
	      if (dt.getTime() <= last) {
	        alert('Error: ' + e.id + ' has an invalid value');
	      }
	      last = dt.getTime();
	    });
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + $row).each(function() {
			array.push($(this).val());
		});
		$('#btnSubmit').click(function(evt) {
    	evt.preventDefault();
    	$.ajax({
            type: "POST",
            url: "Test.jsp",
            data: {array : array},
            success: function(responseFromServer) {
            	 $.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
                    $('#content').html(resultMessageKey);
                });
    	    },
            error: function() {
                alert(" Ajax call Failed to Update Values  into Database ");
            }
        }); 
		});

	});

});
  </script>
  </head>
<body>
	<form action="" method="post">
		<table id="phone" width="100%" name="phone">
			<tr>
				<th>Check/UnCheck</th>
				<th>MYear</th>
				<th>P Date</th>
				<th>Q Date</th>
				<th>B Date</th>
			</tr>
			<%
				for (int i = 0; i < 5; i++) {
			%>
			<tr>
				<td><INPUT type="checkbox" data-row="row<%=i%>" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" value="<%=i%>" size="50"></td>
				<td align="left"><input class="inputText row1" type="text" name="mYear" id="mYear"  value="2020"></td>
				<td><input class="date row<%=i%>"  id="pDate<%=i%>" name="pDate" type="text" value="24/01/2019" /></td>
				<td><input class="date row<%=i%>" id="qDate<%=i%>" name="qDate" type="text" value="28/01/2019" /></td>
				<td><input class="date row<%=i%>" id="bDate<%=i%>" name="bDate" type="text" value="31/01/2019" /></td>
			</tr>
			<%
				}
			%>
		</table>
		<input id="btnSubmit" type="submit" name="submit" value="submit" />
		</p>
	</form>
</body>
</html>

Open in new window

Hi Kim,

I m doing the things like below but how can i make it dynamically its working only for 1 row .

2nd thing that last date date picker calendar enable only date that is after 6 days from present system date.

$(".date1").datepicker({
        dateFormat: "dd/mm/yy",
        minDate: 0,
        onSelect: function (date) {
            var date2 = $('.date1').datepicker('getDate');
            date2.setDate(date2.getDate() + 1);
            $('.date2').datepicker('setDate', date2);
            //sets minDate to dt1 date + 1
            $('.date2').datepicker('option', 'minDate', date2);
        }
    });
    $('.date2').datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function () {
            var dt1 = $('.date1').datepicker('getDate');
            console.log(dt1);
            var dt2 = $('.date2').datepicker('getDate');
            if (dt2 <= dt1) {
                var minDate = $('.date2').datepicker('option', 'minDate');
                $('.date2').datepicker('setDate', minDate);
            }
        }
    });
    
    $('.date3').datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function () {
            var dt2 = $('.date2').datepicker('getDate');
            console.log(dt1);
            var dt3 = $('.date3').datepicker('getDate');
            if (dt3 <= dt2) {
                var minDate = $('.date3').datepicker('option', 'minDate');
                $('.date3').datepicker('setDate', minDate);
            }
        }
    });
    

Open in new window

Dymically, you already did, use the same principle:


<%  
				for (int i = 0; i < 5; i++) {  
			%>  

			use this in your code where you need the number <%=i%>  
ex.   $( "#pDate<%=i%> " ).datepicker({    
  
			<%  
				}  
			%>

Open in new window


use someDate variable if you want 6 days ahead


var someDate  = new Date();
var duration = 6; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

Open in new window

.for 6 days can you give some example in my code itself only it would be very helpful for me thanx a ton in advance.i checked with below code it gives jsp exception.please check below code i tried with one date only -

for(i=0;i<totalRowCount;i++)
		{
		console.log($(".date1<%=i%>"));	
			$(".date1<%=i%>").datepicker({
			dateFormat: "dd/mm/yy",
		    minDate: 0,
		    onSelect: function (date) {
		        var date2 = $(".date1<%=i%>").datepicker('getDate');
		        date2.setDate(date2.getDate() + 1);
		        $(".date2<%=i%>").datepicker('setDate', date2);
		        //sets minDate to dt1 date + 1
		        $(".date2<%=i%>").datepicker('option', 'minDate', date2);
		        //console.log('.date1'+i);
    }
});

Open in new window

Use this if you want the NEXT datepicker to have minimal selection date to be 6  FROM the first:


	$( "#pDate1" ).datepicker({ 
	dateFormat:'dd/mm/yy', 		onSelect: function(d,i){ 
	var someDate  = new Date($( "#pDate1" ).datepicker( "getDate" )); 
	var duration = 6; //In Days 
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000)); 
		$('#qDate1').datepicker('destroy'); 
$("#qDate1").datepicker({dateFormat:'dd/mm/yy', minDate: someDate}); 
if ($( "#pDate1" ).datepicker( "getDate" ) > $( "#qDate1" ).datepicker( "getDate" )) {  
$( "#qDate1" ).val($.datepicker.formatDate("dd/mm/yy", $( "#pDate1" ).datepicker( "getDate" ))) ; 
}      } 
	} )

Open in new window

Change it to:


var someDate  = new Date();

Open in new window

if you wan the next datepicker to be 6 days from TODAY.

Kim Please check my above code for dynamic then i come to this part i want first it should be come for all row. now i m doing like below where "#tableData"  is my table id , beow is only for single date i m writing here once 1st date will work will do it for other date as well as.


      
var totalRowCount = $("#tableData tr").length;
	var rowCount = $("#tableData td").closest("tr").length;
	var message = "Total Row Count: " + totalRowCount;
	message += "\nRow Count: " + rowCount;
	alert(message);
	
	for(i=0;i<totalRowCount;i++)
		{
		console.log($(".date1"+i));	
			$(".date1"+i).datepicker({
			dateFormat: "dd/mm/yy",
		    minDate: 0,
		    onSelect: function (date) {
		        var date2 = $(".date1"+i).datepicker('getDate');
		        date2.setDate(date2.getDate() + 1);
		        $(".date2"+i).datepicker('setDate', date2);
		        //sets minDate to dt1 date + 1
		        $(".date2"+i).datepicker('option', 'minDate', date2);
		        console.log(".date1"+i);
    }
});
		}

Open in new window

Hi Kim ,

i m doing the same as you suggested but still getting error please help me out on this i did only for date1 for testing is date1 is passed then will do it for other date please help me out for this.




[quote]
			var totalRowCount = $("#tableData tr").length;
            var rowCount = $("#tableData td").closest("tr").length;
            var message = "Total Row Count: " + totalRowCount;
            message += "\nRow Count: " + rowCount;
            alert(message);

<%	for(int i=0;i<%>5<%;i++)
		{ %>
	
	$("#date1<%=i%>").datepicker({
        dateFormat: "dd/mm/yy",
        minDate: 0,
        onSelect: function (date) {
            var date2 = $('#date1<%=i%>').datepicker('getDate');
            date2.setDate(date2.getDate() + 1);
            $('#date2<%=i%>').datepicker('setDate', date2);
            //sets minDate to dt1 date + 1
            $('#date2<%=i%>').datepicker('option', 'minDate', date2);
        }
    });
    $('.date2').datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function () {
            var dt1 = $('.date1').datepicker('getDate');
            console.log(dt1);
            var dt2 = $('.date2').datepicker('getDate');
            if (dt2 <= dt1) {
                var minDate = $('.date2').datepicker('option', 'minDate');
                $('.date2').datepicker('setDate', minDate);
            }
        }
    });
    
    $('.date3').datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function () {
            var dt2 = $('.date2').datepicker('getDate');
            console.log(dt1);
            var dt3 = $('.date3').datepicker('getDate');
            if (dt3 <= dt2) {
                var minDate = $('.date3').datepicker('option', 'minDate');
                $('.date3').datepicker('setDate', minDate);
            }
        }
    });[/quote]

Open in new window

"#date1<%=i%>"


has to correspond with the same underneath. Which you already changed a few times, so I can't be sure. In my most recent it would have to been


"#pDate<%=i%>"

Hi Kim ,

I m still getting error please help me out on this my updated code is below -
Please help me out on this and provide solution for this to me in my code because i m getting confused on it please help me out on this thank you a ton in advance.

//$(".date").datepicker({dateFormat:'dd/mm/yy'});
	var totalRowCount = $("#tableData tr").length;
            var rowCount = $("#tableData td").closest("tr").length;
            var message = "Total Row Count: " + totalRowCount;
            message += "\nRow Count: " + rowCount;
            alert(message);
	<%
	for(int i = 0;i < totalRowCount; i++)
		{%>
	
	
	$("#pDate<%=i%>").datepicker({
        dateFormat: "dd/mm/yy",
        minDate: 0,
        onSelect: function (date) {
            var date2 = $("#pDate<%=i%>").datepicker('getDate');
            date2.setDate(date2.getDate() + 1);
            $("#qDate<%=i%>").datepicker('setDate', date2);
            //sets minDate to dt1 date + 1
            $("#qDate<%=i%>").datepicker('option', 'minDate', date2);
        }
    });
    $("#qDate<%=i%>").datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function () {
            var dt1 = $("#pDate<%=i%>").datepicker('getDate');
            console.log(dt1);
            var dt2 = $("#qDate<%=i%>").datepicker('getDate');
            if (dt2 <= dt1) {
                var minDate = $("#qDate<%=i%>").datepicker('option', 'minDate');
                $("#qDate<%=i%>").datepicker('setDate', minDate);
            }
        }
    });
    
    $("#bDate<%=i%>").datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function () {
            var dt2 = $("#qDate<%=i%>").datepicker('getDate');
            console.log(dt1);
            var dt3 = $("#bDate<%=i%>").datepicker('getDate');
            if (dt3 <= dt2) {
                var minDate = $("#bDate<%=i%>").datepicker('option', 'minDate');
                $("#bDate<%=i%>").datepicker('setDate', minDate);
            }
        }
    });
    
	
	<%}%>

Open in new window

You are using two programming languages

Therefore this totalRowCount


<% 	for(int i = 0;i < totalRowCount; i++)  {%>

Open in new window

Is NOT aware of the Javascript  variable totalRowCount

yes the please tell me how can make it dynamic or how can i use my variable totalRowCount because without using this variable we can't change id dynamically.

Since you are in full control over the table data, you probably could also generate it dynamically, and hence, get the rowcount that way.


But to be honest, sad to say, I don't think posting one question will help you out in this project. Usually people are stuck with one thing, and EE can help with that. In your case, it's a whole avalanche of problems, one that's better solved hiring a web developer, who can take a look at the whole picture (whereas I only get to see a glympse).

I can help you better here:  https://www.experts-exchange.com/live/ (obviously, it's paid, but we can do remote sessions, phone calls etc).

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.