gpt4 book ai didi

javascript - 表上 jquery 的总值(value)

转载 作者:行者123 更新时间:2023-12-02 13:49:29 26 4
gpt4 key购买 nike

我尝试使用 jquery 计算表上的总计,但是运行时总计不会出现。所以我想在输入输入值时显示总直播,总自动求和,这是哪里错了?

HTML

<table class="table table-condensed">                                   
<thead>
<tr>
<td class="text-left"><strong>Product</strong></td>
<td class="text-center"><strong>Value</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_a" name="producta" value="12.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_b" name="producta" value="19.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_c" name="producta" value="15.000"></td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong></td>
<td class="thick-line"><input type="text" id="total" name="total" /></td>
</tr>
</tbody>
</table>

JS

jQuery(document).ready(function(){
var total = ($('#product_a').val() + $('#product_b').val() + $('#product_c').val()) ;
$('#total').val(total);
});

最佳答案

你做错了。 val()input[type=text] 上返回一个字符串,目前您只是连接字符串值。

I want to show the total live when I enter the input value

然后,当您键入时输入发生更改时,您需要添加一个监听器。这可以通过 keyup 事件来完成。

例如

$(function() {
var $aProduct = $('#product_a'),
$bProduct = $('#product_b'),
$cProduct = $('#product_c'),
$total = $('#total'),
runTotal = function() {
var a = parseInt($aProduct.val()),
b = parseInt($bProduct.val()),
c = parseInt($cProduct.val());

$total.val(a + b + c);
};

$('.inputVal').on('keyup', runTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong>
</td>
<td class="text-center"><strong>Value</strong>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_a" name="producta" class="inputVal" value="12.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_b" name="productb" class="inputVal" value="19.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_c" name="productc" class="inputVal" value="15.000">
</td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong>
</td>
<td class="thick-line">
<input type="text" id="total" name="total" />
</td>
</tr>
</tbody>
</table>

关于javascript - 表上 jquery 的总值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41113670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com