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 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路