我有一个脚本,它可以实时计算一些字段中的值,当你键入值的时候,它工作得很好。但是,如果我将值发送到数据库,然后从那里取回它们,并从数据库的请求中填充字段,则不再计算字段,除非在已经填充的字段中重新键入它们。
你知道当我从db加载填充的表单时,我如何计算才能启动吗?
这是Jscript
<script type="text/javascript">
$(document).ready(function() {
$('input[id=r],input[id=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[id=r]').val();
var pack = $row.find('input[id=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
if (typeof console == "undefined") {
this.console = {log: function() {}};
}
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
</script>
这是HTML
<tr>
<td></td>
<td>
<div>
<input name="a2c" type="text" size="10" value="<? echo "$a2c";?>">
<input id="r" class="rate" name="a2q" type="text" maxlength="255" size="5" value="<? echo "$a2q";?>">
<input id="p" class="pack" name="a2p" type="text" maxlength="255" size="5" value="<? echo "$a2p";?>">
<span class="amount"></span></div>
</td>
</tr>
<tr>
<td></td>
<td>
<div>
<input name="a3c" type="text" size="10" value="<? echo "$a3c";?>">
<input id="r" class="rate" name="a3q" type="text" maxlength="255" size="5" value="<? echo "$a3q";?>">
<input id="p" class="pack" name="a3p" type="text" maxlength="255" size="5" value="<? echo "$a3p";?>">
<span class="amount"></span></div>
</td>
</tr>
发布于 2012-09-21 22:26:56
你可以做的就是在脚本加载时运行你的函数。为此,一种方法是从.change()中删除匿名函数,并为其命名。
function yourPreviouslyAnonymousFunction() { ... }
$(document).ready(function () {
yourPreviouslyAnonymousFunction();
$('input[id=r],input[id=p]').change(yourPreviouslyAnonymousFunction);
});
因为当页面加载完成时,您的函数不会被调用,因为您使用PHP注入值。这样,当页面加载完成时,您的函数也会运行一次,因此使用您的函数计算这些值。
由于您已经在使用jQuery,另一种方法是强制事件发生:
$(document).ready(function () {
$('input[id=r],input[id=p]').change(function () {
...
// Leave this as is
...
});
$('input[id=r],input[id=p]').change();
});
这是MassivePenguin解释的方式。
发布于 2012-09-21 22:29:36
您可以强制更改事件(以防止代码重复):http://jsfiddle.net/2vqT5/
$(".rate").change();
发布于 2012-09-21 22:25:45
$('input#r').change()
将在id为‘r’的输入上自动触发一个更改事件;这样就足够了吗?
https://stackoverflow.com/questions/12532437
复制相似问题