Jabuka Jabuka - 2 years ago 121
Javascript Question

Binding time difference to each element individually on keyup

I am creating a bunch of transport pickups that occur before a flight departs.

  1. Flight Departure Time

  2. Minutes: number of minutes that pickup occurs before Flight Departs

  3. Pickup Time = Flight Departure Time - Minutes

The Departure Time persists and is used to indicate Pickup Time based on number of minutes prior.

My starting point is;

<label>Flight Departs</label>
<input type="text" class="tour-time" value="10 AM" />
<hr />
<div class="pickups">
<div><label>Pickup Time <span class="pickup-time"></span></label>
<input type="text" class="pickup-minutes" placeholder="number of minutes before flight departs" />
<a href="#" class="add-pickup">Add Pickup</a>

The Add Pickup link adds additional Pickup Times by appending.

My Problem

I would like to update the Pickup Time individually for each Pickup Point added.

I have the times correctly calculated but they all update together. As you can see in following screen shot. The first Pickup Time is correct (20 mins before 10AM = 9:40 AM) but it also changes the second Pickup Time which should be 9:30 AM.


Please see FIDDLE

Thank you.

Answer Source

Your mistake was very simple to spot as you are in-fact only calculating from the first .pickup-minutes element and putting it into every .pickup-time element. Using a simple each function has fixed the issue for me:

$(document).on('keyup', '.tour-time, .pickup-minutes', function()
      var tourtime = $('.tour-time').val();
      var minutes = $(this).find('.pickup-minutes').val();
      ctime = moment(tourtime, 'h:mm A').subtract(minutes, 'minutes').format('h:mm A');

Also: I changed the subtract method to substract(minutes, 'minutes') as it was deprecated in the old way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download