Jabuka Jabuka - 7 months ago 8
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" />
</div>
</div>
<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.

Pickups

Please see FIDDLE

Thank you.

Answer

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()
{
   $(".pickups").children().each(function()
   {
      console.log(this);
      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');
      $(this).find('.pickup-time').html(ctime);
    });
});

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

Comments