如何在jQuery中检测文本输入框中的更改

问题描述 投票:0回答:2

我有两个文本输入文本框,我希望对用户输入的所有内容进行总计。下面是我的代码:

$(document).ready(function(){
    var total = 0;
    $(".test").on("input", function(){
        // Print entered value in a div box
        total += parseInt($(this).val());
        $("#result").text(	total);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
    <p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
    <div id="result"></div>

[当我先输入10时,它需要11,然后,如果我输入100,则它需要111,我不知道为什么会这样。我在哪里出错,请引导我?

javascript jquery input html-input
2个回答
2
投票

尝试这样。

$(document).ready(function(){
    var total = 0;
    $(".test").on("input", function(){
        // Print entered value in a div box
        if (parseInt($("#myInput1").val()) && parseInt($("#myInput2").val())) {
           total = parseInt(parseInt($("#myInput1").val()) + parseInt($("#myInput2").val()));
           $("#result").text(total);
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput2"></p>
<div id="result"></div>

0
投票

total =+ parseInt($(this).val());首先,您必须等于该值,然后打印该数字。基本上,您完成了总和,然后打印了。

$(document).ready(function(){
    var total = 0;
    $(".test").on("input", function(){
        // Print entered value in a div box
        total =+ parseInt($(this).val());
        $("#result").text(total);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
    <p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
    <div id="result"></div>

0
投票

使用更改事件代替输入事件。仅在“提交”值时才会触发,而不是每次击键都将触发。有关详细信息,请参见mdn

© www.soinside.com 2019 - 2024. All rights reserved.