添加多个数组值

时间:2015-10-19 09:00:12

标签: javascript jquery

这是我的表格

<form method="post" action="collect_vals.php">
    <div id="input_fields">
        <div><input type="text" placeholder="unit" name="unit[]"> <input type="text" placeholder="price" name="price[]"><input type="text" placeholder="total" name="total[]"> <span class="fa fa-plus-circle" id="add_field"></span></div>
    </div>
    <input type="submit" value="submit">
</form>

https://jsfiddle.net/d9bhsL4o/1/

这是我的剧本:

<script type="text/javascript">
    $(document).ready(function() {
        $("input[name=unit]").keyup(function() {
            var unit = new Array();
            var qty = new Array();
            $("input[name=unit]").each(function() {
                unit.push($(this).val());
            });
            $("input[name=qty]").each(function() {
                qty.push($(this).val());
            });

            var total = new Array();
            for (var i = 0; i <unit.length; i++) {
                var inp=unit[i]*qty[i];
                ("total["+i+"].value="+inp.value);
            }
        });
    });
</script>

尝试将两个值相乘并保持第三个值。不工作。代码有什么问题

2 个答案:

答案 0 :(得分:4)

在html中附加了类定义,包括渲染和附加元素。我调整你的html代码并使用它来分别对所有值进行总计:

<强> HTML

<input type="text" placeholder="unit" name="unit[]" class="a">
<input type="text" placeholder="price" name="price[]" class="a">
<input type="text" placeholder="total" name="total[]" class="total">

<强> JS

......
......
$("#input_fields").append('<input type="text" placeholder="unit" name="unit[]" class="a"> 
  <input type="text" placeholder="price" name="price[]" class="a">
  <input type="text" placeholder="total" name="total[]" class="total">
  <span id="remove" class="fa fa-minus-circle"></span</div>');
......
......

// capture both unit AND price keyup
$("#input_fields").on('keyup', '.a', function () {
    // add current keyup textbox also into stack
    var all = $(this).siblings('input.a').addBack();
    var sum = 1;
    // loop over those element
    all.each(function(i,e){
        // sum both values
        sum *= $(e).val();
    });
    // finally filtered textbox with total class
    // and assign the output
    $(this).nextAll('.total').val(sum);
});

DEMO

答案 1 :(得分:3)

你应该遍历DOM,有多种方法可以遍历DOM。在这里,我使用.siblings()来获取totalqty

$("#input_fields").on('keyup', "input[name='unit[]']", function () {
    var unit = $(this).val();
    var price = $(this).siblings("input[name='price[]']").val();
    $(this).siblings("input[name='total[]']").val(unit * price);
});