Reputation: 19
I have some database results, I populate them in form, I have this code:
<input type='button' name='add' onclick='javascript: addQty();' value='+'/>
<span><?php echo $records['ct_qty']; ?></span>
<input type="text" class="gridder_input" name="quant[]" class="quant" id="quant[]" />
<input type='button' name='subtract' onclick='javascript: subtractQty();' value='-'/>
So I want to update specific row when the user presses the "quant" button:
function addQty() {
document.getElementById("quant").value++;
}
function subtractQty() {
if (document.getElementById("quant").value - 1 < 0) {
return;
} else {
document.getElementById("quant").value--;
}
updateQuantity();
}
This code works when I have one row, when I have 2 or more rows nothing works, so I probably have to use this word or something?
Upvotes: 1
Views: 58
Reputation: 1156
Ok i dont have a good enough example of your code, but this should be enough to get you in the right direction...
function getTotals() {
var table = document.getElementById('mytable');
for (i = 0; i < table.rows.length; i++) {
var quant = table.rows[i].querySelector('input[name="quant"]').value;
var priceoriginal = table.rows[i].querySelector('input[name="priceoriginal"]').value;
table.rows[i].querySelector('input[name="total"]').value = quant * priceoriginal;
}
}
<table id="mytable">
<tr>
<td>
<input name="quant" type="text" value="2">
</td>
<td>
<input name="priceoriginal" type="text" value="6">
</td>
<td>Total:
<input name="total" type="text">
</td>
</tr>
<tr>
<td>
<input name="quant" type="text" value="8">
</td>
<td>
<input name="priceoriginal" type="text" value="4">
</td>
<td>Total:
<input name="total" type="text">
</td>
</tr>
<tr>
<td>
<input name="quant" type="text" value="5">
</td>
<td>
<input name="priceoriginal" type="text" value="3">
</td>
<td>Total:
<input name="total" type="text">
</td>
</tr>
</table>
<button onclick="getTotals()">Calculate Totals</button>
Upvotes: 0
Reputation: 1156
You can target the neare input using the sibling selectors.
function addQty(elm) {
elm.nextElementSibling.nextElementSibling.value++;
}
function subtractQty(elm) {
if (elm.previousElementSibling.value - 1 < 0) {
return;
} else {
elm.previousElementSibling.value--;
}
updateQuantity();
}
<input type='button' name='add' onclick='javascript: addQty(this);' value='+' />
<span><?php echo $records['ct_qty']; ?></span>
<input type="text" class="gridder_input" name="quant[]" class="quant" id="quant[]" />
<input type='button' name='subtract' onclick='javascript: subtractQty(this);' value='-' />
Upvotes: 1