In my view, I have two date fields like so:
<%= f.text_field :start_date %>
<%= f.text_field :end_date %>
(I’m using the jquery-ui datepicker to set the dates, but left that code out for clarity. Dates are stored in the db as ‘2012-03-02’.)
And I calculate the difference between the two dates with a helper method and display it as #duration:
<div id="duration">
<%= time_diff_in_natural_language(@project.start_date, @project.end_date) %>
</div>
This works as expected – it calculates the difference between the two dates stored in the database. But I’d really like the duration to recalculate on the fly – I’m guessing this would work via a javascript onchange(); event on the date fields that triggers a recalculation of the content in the duration field, but I’m stuck on how to make it happen. Can anyone point me to a good way to accomplish this?
(This question is really similar and I think that answer could work here too, but I can’t figure out how to display the time difference correctly since that would have to reference the rails helper method.)
one approach would be to make an ajax call to get the duration.
so in your controller you would define an action called ‘duration’ for example, which would look for two params, :start_date and :end_date and simply call your helper method time_diff_in_natural_language. Something in the lines of:
Then you can wire up the onSelect event of your date pickers (or the onChange event of the inputs) to call a javascript function, which would simply make an ajax call to the ‘duration’ action in your controller and set the #duration on success. Something like this:
The above is just an example of how you can approach this.