I have a table which is created by a forEach loop (loop through a database). what I'm trying to do is to calculate the price by multiplying qty x rate in each row. I have a JavaScript function(boqMath) to do this, but it only works for the first row(first loop). How can I change it to do this math for every rows(all loops)?
table:
<% user.myrates.forEach(function(myrates){ %>
<tr>
<td><input type='text' class='form-control' value = "<%= myrates.boqUnit %>"></td>
<td><input type='text' class='form-control qty' oninput = "boqMath()"></td>
<td><div class="input-icon"><i>$</i><input type='text' class='form-control rate' oninput="boqMath()" value="<%= myrates.boqRate %>"></div></td>
<td><div class="input-icon"><i>$</i><input type='text' class='form-control price' oninput="boqMath()"></div></td>
<td><button type="submit" name="submit" class="btn btn-primary">Add</button></td>
</tr>
<% }); %>
and this the function:
function boqMath(){
var a = document.querySelector('.qty').value;
var b = document.querySelector('.rate').value;
var price = document.querySelector('.price');
price.value = (Number(a) * Number(b)).toLocaleString();
}
Pass the current element to boqMath()
. From this you can find the closest tr
, and get the inputs in that row.
function boqMath(element) {
row = element.closest("tr");
var qty = row.querySelector(".qty").value;
var rate = row.querySelector(".rate").value;
var price = row.querySelector(".price");
price.value = (qty * rate).toLocaleString();
}
Change oninput = "boqMath()">
to oninput="boqMath(this)"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.