dongya1875
dongya1875
2013-11-21 10:16

jQuery - 输入值更改时更新变量

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...

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douyan1970 douyan1970 8年前

    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);
    });
    
    点赞 评论 复制链接分享
  • dsadasd12132 dsadasd12132 8年前

    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.

    点赞 评论 复制链接分享