Skip to content
Advertisement

Incrementing function argument after jQuery .clone()

I have a php script that prints out price values for current page in a table. Each row is a different price for 1 product and can be edited.

JavaScript

There are 2 functions that calculate based on user input: CalcSale and CalcPerc. Each of them uses the value of the input and the counter $i in order to calculate separately on every row. When a user decides to add a new price and clicks on add_page_price the last row is cloned with:

JavaScript

The question is: How can I clone the last row and increment the argument $i in the onChange = "CalcSale(this.form, $i);"

Advertisement

Answer

How can I clone the last row and increment the argument $i in the onChange = "CalcSale(this.form, $i);"

I wouldn’t do that at all. I’d suggest using modern event handling, probably involving event delegation:

1. Don’t output an onChange attribute on the input elements, but do include either classes or data-* attributes on them (perhaps price-value and regular-price classes).

2. Change the CalcSale function to accept a DOM event.

JavaScript

3. Hook up CalcSale like this:

JavaScript

(Consider adding the input event too: .on("change input"…)

Then your cloning code doesn’t have to worry about incrementing a counter (and it’s easier to remove rows as well), and your existing code works:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement