vivek modi
vivek modi

Reputation: 812

How to auto select date in input type date field

I have two input type="date" fields and I want to auto select second date according to first date.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="first">
<input type="date" id="second">

How to auto select 7 days later date on second input type and want to disabled date before today on second input type date.

Upvotes: 1

Views: 1619

Answers (3)

Ravi Mariya
Ravi Mariya

Reputation: 1230

this is a simple jquery, using stepUp method to add days

today = new Date();
day = today.getDate()
month = today.getMonth() + 1
year = today.getFullYear();

day = day < 10 ? '0' + day : day;
month =  month < 10 ? '0' + month : month;
today = new String(year + '-' + month + '-' + day)
$("#second")[0].min = today;

$('#first').on('change', function(e){
  date = new Date($('#first').val());
  $('#second')[0].valueAsNumber = date.setDate(date.getDate())
  $("#second")[0].stepUp(7);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="first">
<input type="date" id="second">

Upvotes: 0

Akhil Aravind
Akhil Aravind

Reputation: 6130

This will help you to solve your problem, check a deep look :D

jQuery(document).ready(()=>{
  jQuery('#first').change(()=>{
    
    var _date = jQuery('#first').val();
   
    var res = new Date(_date).setTime(new Date(_date).getTime() + (7 * 24 * 60 * 60 * 1000));
    var month = new Date(res).getMonth()+1;
    var day = new Date(res).getDate();
    var output = new Date(res).getFullYear() + '-' +
   (month < 10 ? '0' : '') + month + '-' +
    (day < 10 ? '0' : '') + day;
    
    jQuery('#second').val(output);

})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="first">
<input type="date" id="second">

Upvotes: 3

jun drie
jun drie

Reputation: 872

Check the code below:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="first" onchange="setdate()">
<input type="date" id="second">

<script>
	function setdate(){
		var tt =$('#first').val();

	    var newdate = new Date(tt);
	    var add_value = 7;

	    newdate.setDate(newdate.getDate() + add_value);	  
	
	    var dd = newdate.getDate();
	    var mm = newdate.getMonth() + 1;
	    var y = newdate.getFullYear();

	    if((mm.toString().length)==1){
	    	var mm = '0'+mm;
	    }
	    if((dd.toString().length)==1){
	    	var dd = '0'+dd;
	    }
	    
	    var someFormattedDate = y + '-' + mm + '-' + dd;

	    $('#second').val(someFormattedDate);
	
	}
</script>

Upvotes: 0

Related Questions