這會不會是完美的,但它應該是一個不錯的開始:
您可以在http://jsfiddle.net/qzxf7/
查看該代碼的互動演示,您沒有給我們你的HTML,所以我要去你使用像這樣的假設:
<form action="" method="POST">
<input type="text" name="occurences" id="occurences" value="" />
<input type="text" name="recurringAmt" id="recurringAmt" value="" />
<input type="text" name="totalAmt" id="totalAmt" value="" />
</form>
如果您還沒有處理的Javascript之前,我會建議你使用jQuery是進口的問題jQuery腳本在您的HTML <head>
。
使用jQuery,你可以像這樣的代碼開始,這是過於複雜,但會引發你如何處理殘疾的東西以及價值更新。
/* On page contents loaded */
function updateForm() {
var occ = $('#occurences');
var occV = parseFloat(occ.val());
occV = occV >= 0 ? occV : 0;
var rec = $('#recurringAmt');
var recV = parseFloat(rec.val());
recV = recV >= 0 ? recV : 0;
var tot = $('#totalAmt');
var totV = parseFloat(tot.val());
totV = totV >= 0 ? totV : 0;
/* If total is disabled */
if (tot.attr("disabled")) {
if (rec.val() == '') { /* if no text in rec */
tot.removeAttr("disabled"); /* Reenable total */
tot.val('');
return;
}
/* Otherwise update total */
tot.val(recV * occV);
return;
}
/* If rec is disabled */
if (rec.attr("disabled")) {
if (tot.val() == '') { /* if no text in total */
rec.removeAttr("disabled"); /* Reenable rec */
rec.val('');
return;
}
/* Otherwise update rec watching for divide by zero error */
rec.val(occV > 0 ? totV/occV : 0);
return;
}
/* Otherwise neither disabled */
if (recV > 0) { /* if rec has a number value */
tot.attr("disabled", true); /* disable total */
tot.val(recV * occV); /* update total */
return;
}
if (totV > 0) { /* if total has a number value */
rec.attr("disabled", true); /* disable rec */
/* Update rec watching for divide by zero error */
rec.val(occV > 0 ? totV/occV : 0);
return;
}
}
$(document).ready(function() {
$('#occurences').keyup(function(){
updateForm();
});
$('#totalAmt').keyup(function(){
updateForm();
});
$('#recurringAmt').keyup(function(){
updateForm();
});
});
這工作完美。並感謝現場演示。我已經爲jsfiddle添加了書籤。似乎很方便 – clang1234 2010-08-02 15:39:46