javascript - 如何根据变化的输入进行计算?
问题描述
<!-- This inputs values coming from the date pickers. -->
<input type="text" name="checkin" value="2019-09-11"/>
<input type="text" name="checkout" value="2019-09-13"/>
<input type="text" name="nightprice"/> <!-- When an user write a price -->
<input type="text" name="totalprice"/> <!-- This will be calculated -->
计算会是这样的;
将计算入住和退房之间的天数,并将其乘以天数和价格。
例如 2019-09-11 在 2019-09-13 之间是 2 天,如果用户在 nightprice 上写 200,它将像 2x200 = 400 一样计算,并将放置在 totalprice 输入
我的问题是如何在没有刷新页面的情况下使用 jquery 来做到这一点。
解决方案
这是一个简单的 jQuery 方法。穷人的方法是只听任何input
更改事件并重新运行您的计算。但是,如果您的页面/表单上的输入比这个问题中提到的更多(您可能会这样做),那么我将使用更具体的选择器,而不是简单地收听所有输入。也许去上课?表单提交功能?有很多方法可以处理它。
const calculatePrice = (checkin, checkout, pricePerNight) => {
checkin = new Date(checkin);
checkout = new Date(checkout);
const dayDiff = Math.round( (checkout - checkin) / (1000 * 60 * 60 * 24 ) );
return dayDiff * pricePerNight;
};
$(document).ready( e => {
const nightPriceInput = $('input[name="nightprice"]');
const checkinInput = $('input[name="checkin"]');
const checkoutInput = $('input[name="checkout"]');
const totalPrice = $('input[name="totalprice"]');
$('input').on('change', () => {
const price = calculatePrice(checkinInput.val(), checkoutInput.val(), nightPriceInput.val());
totalPrice.val(price);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This inputs values coming from the date pickers. -->
<input type="text" name="checkin" value="2019-09-11"/>
<input type="text" name="checkout" value="2019-09-13"/>
<input type="text" name="nightprice"/> <!-- When an user write a price -->
<input type="text" name="totalprice"/> <!-- This will be calculated -->