当其他文本框为空或用户输入为零时,设置文本框为零



我这里有一个表,自动计算总成本的基础上您输入的数量。

我的问题是每次我试图移除总成本值的数量值从之前的数量仍然在那里而不是"0"。我只想让它像这样响应:

如果数量文本框有一个值,则计算总成本和

如果用户删除数量中的值,则显示总成本"0"。

任何帮助将非常感激!谢谢你。

这是我到目前为止写的。

<table style="border:1px solid purple">
    <tr>
    <th style="font-size:9px;">COST</th>
    <th style="font-size:9px;">QTY</th>
    <th style="font-size:9px;">TOTAL</th>
    </tr>
    <tr id="Tr1">
    <td><input class="price" type="text" name="price[]" value="100.00"></td>
    <td><input class="qty" type="text" name="qty[]" ></td>
    <td><input type="text" class="output" name="output[]"></td>
    </tr>
    <tr id="Tr2">
    <td><input class="price" type="text" name="price[]" value="100.00"></td>
    <td><input class="qty" type="text" name="qty[]" ></td>
    <td><input type="text" class="output" name="output[]"></td>
    </tr>
    <tr id="Tr3">
   <td><input class="price" type="text" name="price[]" value="100.00"></td>
    <td><input class="qty" type="text" name="qty[]" ></td>
    <td><input type="text" class="output" name="output[]"></td>
    </tr>
    <tr id="Tr4">
   <td><input class="price" type="text" name="price[]" value="100.00"></td>
    <td><input class="qty" type="text" name="qty[]" ></td>
    <td><input type="text" class="output" name="output[]"></td>
    </tr>
</table>
JavaScript

$(document).ready(function() {
    $(this).keyup(function() {
        var grandTotal = 0;
        $("input[name='price[]']").each(function (index) {
            var price = $("input[name='price[]']").eq(index).val();
            var qty = $("input[name='qty[]']").eq(index).val();
            var output = parseInt(price) * parseInt(qty);
            if (!isNaN(output)) {
                $("input[name='output[]']").eq(index).val(output);
            }
        });
    });
});

示例如下:https://jsfiddle.net/bqwnw9Lk/1/

修改后的jsvascript如下,试试这个…

    $(document).ready(function() {
    $(this).keyup(function() {
        var grandTotal = 0;
        $("input[name='price[]']").each(function (index) {
            var price = $("input[name='price[]']").eq(index).val();
            var qty = $("input[name='qty[]']").eq(index).val();
            if( qty == ""){
            output = 0;
            }
            else{
                var output = parseInt(price) * parseInt(qty);
            }

            if (!isNaN(output)) {
              $("input[name='output[]']").eq(index).val(output);

            }
        });
    });
});

如果你想为空数量字段保留输出字段,那么你可以设置
Output = "而不是Output =0;

最新更新