javascript - 为什么 .change() 在 jquery 查询输入值更改后不执行

标签 javascript jquery html

$("body").on('change' , '.pp',function(){
    var price = $(".pp").val();
    price = parseInt(price);
    var quantity = $(".ss").val();
    quantity = parseInt(quantity);
    var amount = (price*quantity);
    $(".rr").val(amount);
    });
/* so from the about what i think is first value was 0 then it is changed to value assigned by the above jquery, until this its working fine but problem arises below, another jquery where severals amount(.pricing) are added and value is assigned to ("#totalAmount") */
    
     $(document).on('change', '.pricing', function() {
        var total=0;
        $(".pricing").each(function(){
            quantity = parseInt($(this).val());
            if (!isNaN(quantity)) {
                total += quantity;
            }
        });
        $("#totalAmount").val(total);
    });
/*  */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Lets suppose i have an input field which has value=0 as given in html -->
<input type="text" value="0" class="rr pricing" name="amount">

    <input type="text" class="ss" name="price">
    <input type="text" class="pp" name="qty">
<!-- Jquery used to set value of input[name="amount"] from these two inputs -->

除非我手动单击 .pricing 输入字段并手动更改它,否则它不会执行,我上面的 jquery 计算不应该更改它的值,因此理论上它应该执行,或者我做错了什么。

最佳答案

change 事件仅在用户更改某些内容时自动触发,而不是在 Javascript 更改内容时自动触发。您需要自己触发它。

更改行:

$(".rr").val(amount);

至:

$(".rr").val(amount).trigger("change");

关于javascript - 为什么 .change() 在 jquery 查询输入值更改后不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48596005/

相关文章:

javascript - 如何修复 <body> 标记上的 "Warning: Unknown prop ` ng-app`。从元素中删除此 Prop “错误?

javascript - 单击浏览器后退按钮时调用 php 函数

javascript - 使用 HighCharts 的条形图脚本无响应和/或响应时间长

jquery - 如何将关闭最小化全屏按钮添加到 Bootstrap 面板

html - 如何使用 Flexbox 制作四个基于视口(viewport)的盒子?

java - 我们如何为循环创建的多个文本框指定相同的名称

javascript - HTML 行已添加,短暂显示,然后消失

javascript - 捕鼠器开火两次

jquery mobile 和 Jquery Jplayer 冲突

javascript - 无法获取动态创建元素的 id