Home > Enterprise >  use same jQuery function for each row (separate values)
use same jQuery function for each row (separate values)

Time:01-14

I want to update a price calculation for each row with jQuery every time the user updates the Quantity in that row.

There are many rows with different items. Each row has its own id. Each row has a Qty input field and a output field with the same classes.

This is the basic HTML relevant to the case:

<div id="item1">
  <div><input  onchange="alterQty()"></div>
  <div><span ></span></div>
</div>
<div id="item2">
  <div><input  onchange="alterQty()"></div>
  <div><span ></span></div>
</div>

and this is the jQuery function I have sofar:


function alterQty() {
  var rowID = $('.itemQty.').parent().parent().attr('id');
  var rowQty = '#'   rowID   ' .itemQty';
  var rowPrice = '#'   rowID   ' .itemPrice';
  iQty = $(rowQty).val();
  var iRetail = "100"; //(For the sake of this question this doesn't matter yet)
  var itemPriceCalc = iRetail * iQty;
  $(rowPrice).text(itemPriceCalc);
};

With the above, what happens is that any Qty updates the price of the first row. And all subsequent rows are not affected. The "rowID" being returned seems to be always "item1"...

What am I missing to make this function work for each specific Qty and give the output only to the Price field in that specific row?

I can write the same function a hundred times using a new name each time but there must be a better way to do this...

CodePudding user response:

Use a jquery function (rather than a DOM onclick=) and you'll get the element that fired the event as this. This will allow you to use relative DOM navigation and remove the '#' rowID

Remove the ID (not needed for this, you may need it for something else) and remove the onclick=

<div>
  <div><input ></div>
  <div><span ></span></div>
</div>
<div>
  <div><input ></div>
  <div><span ></span></div>
</div>

Then add a jquery event using this as the start point.

$(".itemQty").on("change", function() {
  // `this` is now the element being changed

  var row = $(this).parent().parent();
  var rowQty = $(this);
  var rowPrice = row.find(".itemPrice");

  var iQty = $(rowQty).val() * 1;
  var iRetail = "100"; //(For the sake of this question this doesn't matter yet)
  var itemPriceCalc = iRetail * iQty;

  rowPrice.text(itemPriceCalc);   
});

Note that if you add rows dynamically (ie after the page has loaded and after the above code has run) you'll need event delegation. Change

$(".itemQty").on("change", function() {

to

$(document).on("change", ".itemQty", function() {

(ideally use a closer, static element such as $("#rowContainer") instead of document).

  • Related