I want to use jQuery to update a variable (currently a PHP variable, but obviously it will need to be a js variable.) so that when a user changes the value in multiple input fields, it creates a running total that dynamically changes.
Ideally it will also warn when greater than an upper limit.
Current code:
<?php
$counter = 0;
$expected_qty = 24;
?>
<div class="jumbotron text-center">
<p>Running Total:</p>
<h2>
<span class='running_total'>
<?php print $counter; ?>
</span> / <span class='max_qty'>
<?php print $expected_qty; ?>
</span>
</h2>
</div>
<div class="col-xs-12 col-sm-8 col-md-9">
<div class="table-responsive">
<table class="table">
<tr>
<td>
<input class='qty_field' type='number' name='input1' value=''/>
</td>
</tr>
<tr>
<td>
<input class='qty_field' type='number' name='input2' value=''/>
</td>
</tr>
</table>
</div>
</div>
The jQuery currently running on blur is as follows:
$('body').on('blur', '.qty_field', function () {
var sum = 0;
$('.qty_field').each(function() {
sum += Number($(this).val());
});
//Write sum to run
$('running_total').html(sum);
});
I was hoping the
Although not implemented in the example, there is functionality to dynamically add more table rows, but the script already takes this into account
Edit - Updated with more detail...
With a few tweaks to the JS and HTML, the following code works...
$('body').on('keyup', '.qty_field', function () {
var sum = 0;
$('.qty_field').each(function() {
sum += Number($(this).val());
});
$('.running_total').html(sum);
});
This is a typical case of using AngularJS. Take a look on that. With jQuery it will be a horror to implement this. With Angular, only few lines of code.