Get month and year from one input to others

I woull like to dynamic populate field month and year when i write on date on first field

<input id="dateField" type="date"></input>
<input id="month" type="text"></input>
<input id="year" type="text"></input>

<script>
var month= $("input[type='text'][id='month']");
var month= $("input[type='text'][id='year']");
$(dateField).keypress(function(){
//help me construct this
    month.val()
year.val()
});
</script>

var d = new Date();
var m = d.getMonth();
var y = d.getFullYear();

These will get the month and year.
To set the fields, use something like this:

document.getElementById(‘month’).value = m;
document.getElementById(‘year’).value = y;

You could combine these two lines for each one, but, wanted to explain them separately first.
Hope this helps…

1 Like

Thank you it works!
function _month() {

	var d = new Date($("input[type='date'][id='mydate']").val());
	var m = d.getMonth();
	var y = d.getFullYear();

	document.getElementById("mymonth").value = m+1;

}

Can help set expired date for more 1 month or 15 days.

I try var month = date.getMonth() + 2; but not work on December

it needs to be fixed

<script type="text/javascript">	
function date_expired(action) {
  if (action == 'set expiry date') {
    var date = new Date($('#StartDate').val());

    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();
    if (month < 10) {
      month = '0' + month;
    }

    if (day < 10) {
      day = '0' + day;
		
    }

    var show = (year + '-' + month + '-' + day);
    $('#EndDate').val(show);
  }
}	
</script>	


<input type="date" class="form-control arial no-radius" id="StartDate" onchange="date_expired('set expiry date')" />

<input type="date" class="form-control arial no-radius" id="EndDate" disabled/>

Example…

var datetoday = new Date(2018, 0, 31);
var dateplus  = datetoday.setMonth(datetoday.getMonth()+2);

So, the first part sets up a date variable.
Then, adds 2 months to it.

1 Like

Thank you @ErnieAlex. It works!!!

<script type="text/javascript">	
function date_expired(action) {
  if (action == 'set expiry date') {
    var datetoday = new Date($('#StartDate').val());

  
	var dateplus  = datetoday.setMonth(datetoday.getMonth()+1);
	var day = datetoday.getDate(); 
    var month = datetoday.getMonth() + 1;
    var year = datetoday.getFullYear();
 
	  
    if (month < 10) {
      month = '0' + month;
    }

    if (day < 10) {
      day = '0' + day;
		
    }

    var show = (year + '-' + month + '-' + day);
    $('#EndDate').val(show);
  }
}	
</script>
Sponsor our Newsletter | Privacy Policy | Terms of Service