'JavaScript to update End Date when Start Date is changed

For the site I am developing, I use a form to update the different fields of a model.

Some of those fields need to be updated according to the values of others. For example, each instance of a Task, has a start date, an end date, and a length which have to verify the following : End = Start + Length (where weekends are not counted, but that is a secondary issue).

So one of the functions I am trying to write would do :

When the user changes the value of the input Start_date
Get that date from the input field
Get the value of the field Length
Update the value of the input "End date" with (Start_date + Length)

The three inputs concerned by my example have the following IDs : id_start, id_length, id_finish.

Here is what I have written, but which doesn't work at all (nothing visible happens...) :

<script>
    $( "#id_start" ).change(function() {
        var start = new Date();
        var finish = new Date();
        var numberOfDays = document.getElementById('id_length').value;
        start = document.getElementById('id_start').value;
        finish.setdate(start.getDate()+document.getElementById('id_length'))
        $('#id_finish').val(finish);
    });
</script>

Any hint at a solution to make it work would be hugely appreciated.



Solution 1:[1]

Let's look at what your code is actually doing.

var start = new Date();

Here you create a new Date object.

start = document.getElementById('id_start').value;

Here, you change the value of start to the value of the DOM element with the id = 'id_start'. The problem is, this value isn't a Date object. Even the new HTML Date input type (which isn't supported by Firefox or IE) will only give you a string when you pull it's value. So you've created a new Date object, and then you throw it out immediately.

So now start isn't a Date, but a string. In this line:

finish.setdate(start.getDate()+document.getElementById('id_lenght'))

You're attempting to call the undefined .getDate() on a string object, so you'll get an error.

Here's what you need to do. That string (assuming it's in ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS) can be used to create a new Date.

start = new Date(document.getElementById('id_start').value);

Now start is actually a date object, and you can add the length in days to get your end date.

Of course, you'll want to make sure the input is in an acceptable format! There's a lot of 'date picker' options (jQueryUi, for example, has a datepicker), and if you're only interested in supporting Chrome, the works well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Travis Clark