0

I have two text boxes in my application. In the first text box user enters the date in yyyy/mm/dd format. Then I need to take the system date and find the difference between the two dates in months, which I am able to do it using javascript. Now I need to populate the second text box with that difference. How this can be achieved?

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
Firoz
  • 488
  • 2
  • 6
  • 21

2 Answers2

1

Something like this (calculates difference in msecs):

EDIT re-written for onkeyup event

HTML:

<input id="initialDate" onkeyup="checkDiff(this.value)"/>
<input id="diff"/>

JS:

function checkDiff (initialDate) {
    if (initialDate.length == 10){
        var dateParts = initialDate.split("/");
        var date = new Date(dateParts[0], dateParts[1]-1,dateParts[2]);
        var diff = document.getElementById('diff');
        var now = new Date();
        diff.value = (now-date);
    }
}

JSFiddle: http://jsfiddle.net/8haJX/

nikis
  • 11,166
  • 2
  • 35
  • 45
  • i need to do this without having a button click.How can I achieve this. – Firoz Feb 14 '14 at 17:23
  • what event do you want to use in such a case? – nikis Feb 14 '14 at 21:04
  • That is what i am thinking to implement i am not getting any thing.Please suggest me – Firoz Feb 15 '14 at 07:13
  • If you don't like buttons, you can use `onKeyUp` event. I've edited answer accordingly – nikis Feb 15 '14 at 09:38
  • this is exactly what I am looking for. I need to populate the second text box with moths between the two date. i,e i need to calculate the no of months between the two dates and I am accepting the data in yyyy/mm/dd format from the user. – Firoz Feb 15 '14 at 13:44
  • slightly modified example http://jsfiddle.net/8haJX/1/ with months (I've used a function from here http://stackoverflow.com/questions/2536379/difference-in-months-between-two-dates-in-javascript) – nikis Feb 15 '14 at 13:58
0
document.getElementById('textbox_id').value = difference;

where the variable difference is your calculated difference.

display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41