Andrew
Andrew

Reputation: 11

Updating one element after another updates

I'm working on a page in which one element ('.item--itemprice') updates its text through another function that I'd prefer not to touch. What I'd like to do is get another element ('.header--itemprice') to update so that its text matches the first element.

Unfortunately, it seems that handler below is acting faster than the updating function. As a result, the header either stays with the previous text or changes to a blank string. Is there a way to delay the final line below until after the first element is finished updating?

$('select').on('change', function() {
   const headPrice = document.querySelector('.header--itemprice');
   const lowerPrice = document.querySelector('span.item--itemprice');
   const $lowerText = $(lowerPrice).text();
   $(headPrice).text($lowerText);
});

Here's the preexisting function:

$(document).ready( function () {
  $('#txtQuantity, .ProductGroupItemQuantity').blur(updatePrice);
});

function updatePrice() {
  var itemPriceEl = $('.item--itemprice');
  var itemCountEl = $('#txtQuantity');
  var groupUpdateEl = $('#lnkProductGroupUpdatePrice');
  var groupPriceEl = $('.pdetail--price-total');
  var totalPriceEl = $('.ProductDetailsPricing');
  var itemPrice = moneyToNumber(itemPriceEl.text());
  var itemCount = moneyToNumber(itemCountEl.val());
  var itemTotalPrice = itemCount * itemPrice;
  var groupTotalPrice = 0;

  // Trigger Group Update
  groupUpdateEl.click();
  groupTotalPrice = moneyToNumber(groupPriceEl.text());

  // Calculate Total Price
  totalPriceEl.text('Total: $' + Number(groupTotalPrice + itemTotalPrice) / 100);
}

/*$('select').on('change', function() {
  const headPrice = document.querySelector('.header--itemprice');
  const lowerPrice = document.querySelector('span.item--itemprice');
  const $lowerText = $(lowerPrice).text();
    $(headPrice).text($lowerText);
});*/

function moneyToNumber(moneyEl) {
  try {
    return Number(moneyEl.replace(/[^0-9\.]+/g,"").replace(/\D/g,''));
  } catch (err) {
    return 0;
  }
}

Upvotes: 1

Views: 196

Answers (2)

Augusto Monteiro
Augusto Monteiro

Reputation: 491

In that case, the better way is changing the function, you can even trigger a event when the function is executed and watch this event to trigger the other function to change the element ('.header--itemprice')

Upvotes: 0

Akhil
Akhil

Reputation: 629

If you don't want to touch the other function at all and assuming it is also being called on the change event of select. A really hacky way could be, something like this -

$('select').on('change', function() {
setTimeout (function()
{
   const headPrice = document.querySelector('.header--itemprice');
   const lowerPrice = document.querySelector('span.item--itemprice');
   const $lowerText = $(lowerPrice).text();
   $(headPrice).text($lowerText);
}, 0);
});

Upvotes: 1

Related Questions