我正试图编写一个jquery脚本,将ID中包含"*Amount"的所有文本字段相加。我有以下内容,但不知道如何将它们相加并将值分配给不同的文本框。
<input type="text" id="1stAmount">
<input type="text" id="2ndAmount">
<input type="text" id="3rdAmount">
// to get all the values of the textboxes that have Amount in the ID
$( "input[name*='Amount']" ).value();
您可以使用"[id*=Amount]"获取id与Amount
匹配的所有输入。此外,.val()
是检索输入值的方法。然而,这只检索第一个匹配的值:
$('[id*=Amount]').val(); // will be the first input's value
要检索所有值,必须循环遍历返回的集合中的每个元素,并将值相加:
var total = 0;
$('[id*=Amount]').each(function(element) {
// get the value of the current element
var text = $(this).val();
// add the parsed total
total += parseFloat(text );
});
// do something with total here
alert(total)
JsFidle示例http://jsfiddle.net/2xpNa/
试试这个:
var values = $( "input[name*='Amount']" ).value();
var sum = 0;
for (int i=0;i<values.length;i++){
sum += parseInt(values[i]);
}
$("#yourTextbox").val(sum);
您不能使用[name*=Amount]
获取带有ID的文本框,请使用[id*=Amount]
使用.each()
JSFIDDLE演示
var ids = $('[id*=Amount]');
var count = 0;
$.each(ids,function(){
count += parseFloat(this.value);
});
alert(count);