我刚刚开始使用jQuery和JS。我试图根据其他字段动态设置首付款字段和主要字段,但可以手动设置首付款和原则字段。他们只需要加起来估算价值/评估字段。还有一种奇怪的行为,如果我在具有自动填充字段的字段中输入值,它将保留其原始值。有什么想法吗?
//autocalculate downpayment
function computeD (){
var value = $("#edit-field-estimated-value-und-0-value").val();
var appraised = $("#edit-field-appraisal-amount-und-0-value").val();
var mort1 = $("#edit-field-1st-mortgage-und-0-value").val();
var princ = $("#edit-field-amount-new-und-0-value").val();
var down = $("#edit-field-down-payment-und-0-value").val();
function realVal () {
var propValue;
if (appraised === ""){
propValue = value;
} else {
propValue = appraised;
}
return propValue;
}
var princP = realVal() - mort1 - down;
var downP = realVal() - mort1 - princ;
$("#edit-field-down-payment-und-0-value").val(downP);
$("#edit-field-amount-new-und-0-value").val(princP);
}
//autocalculate down payment based on mort1 and princ
$("#edit-field-estimated-value-und-0-value,#edit-field-appraisal-amount-und-0-value, #edit-field-1st-mortgage-und-0-value,#edit-field-amount-new-und-0-value,#edit-field-down-payment-und-0-value").change(computeD);
答案 0 :(得分:0)
每次对原则和预付款输入字段进行更改时,将调用确定原则和预付款输入字段值的函数并覆盖其值:
var princP = realVal() - mort1 - down;
var downP = realVal() - mort1 - princ;
$("#edit-field-down-payment-und-0-value").val(downP);
$("#edit-field-amount-new-und-0-value").val(princP);
因此,当用户手动更改这些字段时,会调用computeD(),并且会覆盖其更改。如果您不想重新计算这些值,请在更改这些字段的值时调用computeD():
//autocalculate down payment based on mort1 and princ
$("#edit-field-1st-mortgage-und-0-value, #edit-field-appraisal-amount-und-0-value, #edit-field-estimated-value-und-0-value").change(computeD);
此外,您可以使用disabled
属性确保他们无法手动更改字段的值(如果这是您的意图):
<input class="text-full form-text required" type="text" id="edit-field-amount-new-und-0-value" name="field_amount_new[und][0][value]" value="" size="10" maxlength="255" disabled>