【发布时间】:2010-11-22 23:04:57
【问题描述】:
我正在努力让我认为应该是一个简单的 jquery/javascript 工作。我有一个文本框和 2 个收音机,因此我想在用户更改其值时自动更新“总”文本框:
<tr>
<td>Value:</td>
<td>
<input name="value" type="text" id="value" />
</td>
</tr>
<tr>
<td>Postage:</td>
<td>
<input id="express" type="radio" name="postageradio" value="PostageExpressRadio" />
Express post ($3.50)
<input id="registered" type="radio" name="postageradio" value="PostageRegisteredRadio" />
Registered post ($5.00)
</td>
</tr>
<tr>
<td>Total:</td>
<td colspan="2">
<input name="total" type="text" readonly="readonly" id="total" />
</td>
</tr>
这是我想出的一点 jquery,它在 Chrome 中效果不佳(更新速度很慢),并且在 IE 中根本不适用于收音机。我确信有更好的方法可以做到这一点,因此欢迎提出任何建议。
function calctotal() {
var value = $('#value').val();
var amount = parseInt(value.replace(' ', '').replace('$', ''));
if (isNaN(amount)) amount = 0;
var post = 0;
if ($('#express').is(':checked')) post = 3.5;
if ($('#registered').is(':checked')) post = 5.0;
$('#total').val('$' + (amount + post).toFixed(2));
}
// The timeout is used because otherwise the 'change' events get the previous value (???)
function calctotalsoon() {
setTimeout(function() {
calctotal();
}, 100);
}
$(document).ready(function() {
$('#value').keyup(function(event) {
calctotalsoon();
} );
$('#express').change(function(event) {
calctotalsoon();
} );
$('#registered').change(function(event) {
calctotalsoon();
} );
} );
非常感谢
【问题讨论】:
-
对我来说似乎在 Chrome 和 IE8 中运行良好。你用的是什么版本的jQuery?
-
找到了更多关于收音机为什么不能在 IE 中触发的细节:norman.walsh.name/2009/03/24/jQueryIE
-
是的,看起来您可能想要添加一个 .click 方法来处理 IE“功能”。
-
哇,我以为 jquery 已经为你解决了所有跨浏览器的问题?
-
另外,我希望它在他们在“值”框中键入每个字符时更新,而不是等到它失去焦点。我需要哪一个 keydown/up/press?
标签: javascript asp.net jquery html