当另一个字段值发生更改时,如何使用jQuery更改字段

我搜索了甚至像JQuery这样的答案:当其他输入字段的值改变时更改值 ,我无法弄清楚这一点。

我试图根据HTML表单输入做一些数学运算。 当用户在第一个和第二个字段中输入数字时,我希望它自动计算到第三个字段以显示总数。

我的表单代码是:

Enter Recurring Gift Amount: $
I would like to make this gift for months.
Total Gift Amount of $.

我试图运行的javascript是:

 function replaceRecurringDonationValue() { //make our variables so we don't forget var perDonationValue = 0; var numberOfMonths = 0; var TotalRecurringDonationValue = 0; //give them their correct values perDonationValue = $("#recurringDonationValue").val(); numberOfMonths = $("#numberOfMonths").val(); //ensure that the maximum number of months is enforced. if(numberOfMonths > 60) { alert("Donations can last for a maximum of 60 months."); $("#numberOfMonths").val(60); } TotalRecurringDonationValue = perDonationValue * numberOfMonths; $("#TotalRecurringDonationValue").val(TotalRecurringDonationValue); } $("#recurringDonationValue").change(replaceRecurringDonationValue()); $("#numberOfMonths").change(replaceRecurringDonationValue()); 

如果您想查看完整的主页源代码: http : //pastebin.com/aLMqYuxc和完整的javascript源代码是: http : //pastebin.com/FvviPHhj

对不起,如果这是一个愚蠢的问题,谢谢大家的帮助。 我还在努力解决这个问题。

尝试改变这个:

 $("#recurringDonationValue").change(replaceRecurringDonationValue()); 

对此:

  $("#recurringDonationValue").change(function(){ replaceRecurringDonationValue(); }); 

还有这个:

 $("#numberOfMonths").change(replaceRecurringDonationValue()); 

对此:

 $("#numberOfMonths").change(function(){ replaceRecurringDonationValue() }); 

安德斯的好评,

更好地结合两个选择器,例如

  $("#recurringDonationValue, #numberOfMonths").change(function(){ replaceRecurringDonationValue(); }); 

少代码保持干燥(不要重复自己):)

三件事…

改变这个:

 Total Gift Amount of $. 

对此:

 Total Gift Amount of $. 

改变这个:

 $("#TotalRecurringDonationValue").val(TotalRecurringDonationValue); 

对此:

 $("#totalRecurringDonationValue").val(TotalRecurringDonationValue); 

最后,改变这个:

 $("#recurringDonationValue").change(replaceRecurringDonationValue()); $("#numberOfMonths").change(replaceRecurringDonationValue()); 

对此:

 $("#recurringDonationValue,#numberOfMonths").change(replaceRecurringDonationValue);