簡體   English   中英

從Javascript中的多個文本框中獲取值

[英]Getting values from multiple text boxes on keypress in javascript

我的表單中有8個不同的文本字段,這是客戶賬單的一部分。 這里是

<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事件附加到每個文本字段

`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');
    }
}

但是效果不好

您可以使用傳遞給鍵偵聽器的事件的target.value屬性-這將為您提供輸入字段的值:

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

只需將其添加到正在運行的總計中,然后更新偵聽器功能內的文本即可。

您可以在keyup事件中獲得所有具有form-control類的輸入的keyup如下所示:

 $('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" > 

我已經用JavaScript而不是jQuery進行了定義。 試試吧..

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM