dongya1875 2013-11-21 10:16
浏览 186
已采纳

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 2013-11-25 20:29
    关注

    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);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog