根据表单中的字段值输出实时计算

根据表单中的字段值输出实时计算

问题描述:

我想使用jQuery在窗体中输出实时计算,但是由于缺乏JS知识,我不确定从哪里开始.我想知道是否有人可以帮助我吗?

I'd like to output a live calculation in a form using jQuery, but I'm not sure where to start due to my lack of JS knowledge. I wonder if anyone can help me with this please?

这是我的字段值:

<input type="hidden" name="total_days" value="{total_days}" />
<input type="text" name="cost_per_day" value="" />
<p>Total Cost: $<span class="total_cost"></span></p>

当页面加载时,total_days将被预先填充一个值. cost_per_day将由用户输入.我希望在用户输入表单时填充total_cost范围,计算方法如下:

The total_days will be pre-filled with a value when the page loads. The cost_per_day will be entered by the user. I'd like the total_cost span to populate as the user types into the form, and the calculation is this:

total_days * cost_per_day = total_cost

我在您的隐藏文本字段和用户文本字段中添加了一个ID以检索其值.

I have added an id to your hidden text field and the user text field to retrieve their values It looks something like this .

<input type="hidden" name="total_days" id = "totaldays" value="10" />
<input type="text" name="cost_per_day" id = "mytextfield" value="" />
<p>Total Cost: $<span class="total_cost"></span></p>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

javascript如下:

The javascript goes as follows:

$("#mytextfield").on('keyup',function(){
        var totalcost= $("#totaldays").val() * $(this).val() 
        $(".total_cost").html(totalcost);
})

希望这会有所帮助.