1

クライアントがサービスの費用を確認し、テキスト入力の変更に基づいて結果を更新できるように、計算機として作成している非常に単純なスクリプトがあります。問題は、最初の回避後に値が正しく計算されなくなることです。ここにあります、助けて感謝します。

<script>
$(function(){


var one=0;
var two=0;
var three=0;
$("input:text").change(function(){
if($(this).val() == $('#first').val())
{ 
 one = parseInt($(this).val());



}
 else if($(this).val() == $('#second').val()){

two = parseInt($(this).val());

 }
 else if($(this).val() == $('#third').val()){

three = parseInt($(this).val());

 }

});


$('input:text').change(function(){

$('#result').text(one+two+three);


});


});


</script>

そしてフォーム:

<div id="container">
<form action="something.html" id="subit">
<label for="first">put numbers</label><input type="text" id="first"/>
<label for="second">more numbers</label><input type="text" id="second" value="0"/>
<label for="third">and more numbers</label><input type="text" id="third" value="0"/>
<input type="submit" />
</form>
<div id="result"></>
</div>
4

1 に答える 1

1

このコードを試してください

$(document).ready(function() {
    var textboxes = $("#container input:text");
    textboxes.on("keyup", function() {
        var amt = 0;
        textboxes.each(function() {
            amt += +$(this).val();
        });
        $("#result").html(amt);
    });
});​

作業フィドル: http://jsfiddle.net/naveen/87p53/


コードに関しては、コードでこれらを変更します

を。値ではなく ID を比較すると、はるかに安全です。
b. 2 番目の変更機能を削除します。まったく必要ありません。

$(function() {
    var one = 0;
    var two = 0;
    var three = 0;
    $("input:text").change(function() {
        if (this.id == "first") {
            one = parseInt($(this).val());
        }
        else if (this.id == "second") {
            two = parseInt($(this).val());
        }
        else if (this.id == "third") {
            three = parseInt($(this).val());
        }
        $('#result').html(one + two + three);
    });
});​
于 2012-04-23T02:47:04.290 に答える