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

标签 javascript jquery html forms

我进行了搜索,甚至找到了类似 JQuery: Change value when value of other input field is changed 的答案,我一直无法弄清楚这一点。

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

我的表单代码是:

<div id="makingARecurringGift">
    Enter Recurring Gift Amount: $<input type="number" min="0" name="recurringDonationValue" id="recurringDonationValue" size="15" value="0" /><br />
    I would like to make this gift for <input type="number" min="0" max="60" name="numberOfMonths" id="numberOfMonths" size="15" value="0" /> months.<br />
    Total Gift Amount of $<input type="number" min="0" value="0" name="totalRecurringDonationValue" />.
</div>

我尝试运行的 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();
                                           });

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

关于javascript - 当另一个字段值更改时,如何使用 jQuery 更改字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13766568/

相关文章:

javascript - 我可以获得一些关于带有图像按钮的列表控件的建议吗?

javascript - Jquery 数据表在 IE9 上呈现缓慢

javascript - 使用 jquery 在选中/未选中的复选框上添加/删除值

javascript - 从javascript中的createRange中删除内容

javascript - jQuery 动画设置回调抛出错误

javascript - Mobiscroll Numpad 自定义预设

javascript - 正确附加具有正确索引的多个元素 <div>

javascript - 对于验证是否可以在按键事件上使用模式属性

html - 如何设置 HTML5 表单验证消息的样式?

javascript - 增加 d3 SVG 容器大小