[英]jQuery: How to add float values in multiple fields using class name
Using jQuery, I have float values in fields with similar class names " score "and I just want to make a function that will add all float values in those fields and assign the result to " field5 ". 使用jQuery,我在具有相似类名“ score ”的字段中具有浮点值,而我只想创建一个函数,该函数将在这些字段中添加所有浮点值并将结果分配给“ field5 ”。
<input id="field1" type="text" class="score">2.5</input>
<input id="field2" type="text" class="score">6.02</input>
<input id="field3" type="text" class="score">1</input>
<input id="field4" type="text" class="score">4.03</input>
<input id="result" type="text" class="result"></input>
I made the script below but it doesn't work even though the function executes. 我在下面创建了脚本,但是即使函数执行了,它也无法正常工作。
$(.score).on('change',function(){
var total = 0
$(this).each(function(){
total += this.value;
});
});
$('#result').val(total);
});
Lot of issues in your code: 您的代码中有很多问题:
JS: JS:
$(".score").on('keyup', function () {
var total = 0
$(".score").each(function () {
total += parseFloat(this.value);
});
$('#result').val(total);
});
HTML 的HTML
<input id="field1" type="text" class="score" value="1"/>
<input id="field2" type="text" class="score" value="1.2"/>
<input id="field3" type="text" class="score" value="1.4"/>
<input id="field4" type="text" class="score" value="3.1"/>
<input id="result" type="text" class="result" value=""/>
Demo: http://jsfiddle.net/GCu2D/839/ 演示: http : //jsfiddle.net/GCu2D/839/
$(".score")
instead of $(this)
to get all input values. $(".score")
而不是$(this)
来获取所有输入值。 Latter will give only the current input's value. .value
. .value
获取字符串值。 In order to add them, you need to convert them to float $(.score)
is invalid. $(.score)
无效。 Use $(".score")
. $(".score")
。 $('#result').val(total);
should be inside the event handler. First of all, I believe .change() is used with dropdowns. 首先,我相信.change()与下拉列表一起使用。 Try using
.keydown()
to detect a change in an input box. 尝试使用
.keydown()
来检测输入框中的更改。
There are a few errors in your code - 您的代码中有一些错误-
var total = 0;
Semicolon is missing. 分号丢失。
$('#result').val(total);
This will assign the value and will not show it. 这将分配该值,并且不会显示它。 If you wish to display teh value as well, use
如果您还希望显示该值,请使用
$('#result').append(total);
$(document).ready(function(){
$(".score").on('change',function(){
var total = 0.00;
$(".score").each(function(){
if(undefined != $(this).val() && "" != $.trim($(this).val()))
total += parseFloat($(this).val());
});
$('#result').val(total);
});
});
I finally figured it out. 我终于弄明白了。 Thanks guys!
多谢你们!
function getResult(){
var total = 0;
$('.score').each(function(){
var checkval= parseFloat(this.value);
if(!isNaN(checkval)) total += checkval;
});
$('#result').val(total.toFixed(2));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.