2016-05-17 15 views
0

フォームに8種類のテキストフィールドがありますが、これは顧客請求書の一部です。 は、ここでは、私が合計値としてすべての値の合計を表示したい。このことから複数のテキストボックスから値を取得するJavaScriptのkeypressで

<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty"> 
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation"> 
...... 

up to 8 

ある

<span>Total extra cost:1678</span> 

どのようにすることができます任意のテキストフィールドの値が変更されたときに変更し、そうしなければなりません私は完全にkeyupイベントを使用してそれを行うのですか?私は、各テキストフィールドにonkeyupのイベントを添付した

UPDATE

`onkeyup="findSum(this.value)"' 

と私は店のためのグローバル配列を使用していた入力はvar extras=[]

function findSum(value) 
{ 
    if(value!=''){ 
     console.log(value); 
     extras.push(parseInt(value)); 
     if(extras!='') 
     $('#extratotal').text(extras.reduce(getSum)); 
     else $('#extratotal').text('0'); 
    } 
} 

しかし、そのない値よく働いた

+2

これまでに何を試みましたか? – Dacaspex

答えて

1

あなたはこのようなkeyupイベントにform-controlクラスを持っているすべての入力のSUM取得することができます:私はJavaScriptの代わりにjQueryの中で定義されている

$('input.form-control').on('keyup',function() { 
 
    var total = 0; 
 
    $('input.form-control').each(function(){ 
 
     if (this.value == ''){ 
 
      total += parseInt(0); 
 
     }else{ 
 
      total += parseInt(this.value); 
 
     } 
 
    }); 
 
    $('#total').val(total); 
 
});
input { 
 
    display: block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty" > 
 
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation" > 
 
<input type="text" name="other" class="form-control" placeholder="other" > 
 

 
Total extra cost: <input id="total" >

+0

それは解雇されませんでした –

+0

部分的になっていましたが、「NAn」を取得しました –

+0

@BlessanKurien非常に奇妙なことに、私にとっては完璧に機能します。 –

2

あなたは、キーリスナーに渡されたイベントのtarget.valueプロパティを使用することができます - これはあなたの入力フィールドの値を与える:

document.addEventListener('input', 'keyup', function(e) { 
    // use e.target.value here 
} 

ただ実行中の合計にこれを追加し、リスナー関数内のテキストを更新します。

1

を。試してみてください。

<script> 
function sum() 
{ 

    var sum = 0; 
    var array_field = document.getElementsByClassName('sum_field'); 
    for(var i=0; i<array_field.length; i++) 
    { 
     var value = Number(array_field[i].value); 
     if (!isNaN(value)) sum += value; 
    } 
    document.getElementById("total").innerHTML = sum; 
} 
</script> 
<body> 
    <input type="text" name="txtcustomduty" class="form-control sum_field" placeholder="Customs Duty" onkeyup="sum()"> 
    <input type="text" name="txtlcltranspotation" class="form-control sum_field" placeholder="Local Transportation" onkeyup="sum()"> 
    <p>Total:<span id="total">0</span></p> 
</body> 
関連する問題