如何通过name属性从倍数输入中获取值?

时间:2018-03-28 17:57:25

标签: jquery

<input type="text" class="form-control" id="Preco0" name="produtosBonificacao[0].Preco" value="" placeholder="Preço Sistema" readonly="readonly">

<input type="text" class="form-control" id="Preco1" name="produtosBonificacao[1].Preco" value="" placeholder="Preço Sistema" readonly="readonly">

我必须得到这些值并总结所有这些......

function subotal() {
    var sum = 0.0;
    $('input[name^="produtosBonificacao[].Preco"]').each(function () {
        var price = $(this).val();
        sum += price;
    });
    //I need to set the sum in readonly input. 

}

之后,我需要在某处设置总和。

2 个答案:

答案 0 :(得分:0)

您需要使用的选择器是$('input[name^="produtosBonificacao"]'),并且要添加总和,您需要将输入的值转换为整数。

function subotal() {
    var sum = 0;
    $('input[name^="produtosBonificacao"]').each(function () {
        if($(this).attr('name').indexOf('.Preco') === -1) {
            return;
        }
        var price = parseInt($(this).val());
        sum += price;
    }); 
}

答案 1 :(得分:0)

请看下面的例子,可能会有帮助[请参阅评论说明]

function subotal() {
   var sum = 0.0;
   //1. get input elements whose name starts with "produtosBonificacao"
   $('input[name^="produtosBonificacao"]').each(function () {
        //2. Make sure that input belongs to "Preco" property
        if($(this).attr('name').indexOf('.Preco')>-1)
        {
           //3. Parse value, for this example just use parseInt
           //Make sure that you don't need parseFloat.
           //Before using parsed value into sum, just make sure that it is valid number.
           var price = parseInt($(this).val());
           sum += (isNaN(price)?0: price);
        }
    });
    //I need to set the sum in readonly input. 
    alert(sum);
}
$(document).ready(function(){
subotal();

})

https://jsfiddle.net/vrluckyin/4j71uc93/11/