I found this code online and am unable to get it to work correctly can someone please tell me where I am going wrong? The description made it sound like it will work exactly how I need it to but for some reason I cannot get it to work correctly on my end. I have been putting a bunch of alerts and cannot even get them to display. I am sorry I am very new trying to teach myself JavaScript.
Input button:
<cfinput
type="datefield"
name="purchasedate"
width="130"
required="yes"
message="Please enter purchase date."
value="#dateformat(now(),"mm/dd/yyyy")#"
oninput="calculateTotal();"
>
JavaScript Function:
function getDatePrice(date) {
var datePrice = 0
var theForm = document.forms["form"];
var purchasedate = theForm.elements["purchasedate"];
var date = new Date(purchasedate.value);
if (Object.prototype.toString.call(date) !== '[object Date]') {
date = new Date();
}
var today = new Date();
var diffMilli = today - date;
var diffDays = diffMilli * 1000 * 60 * 60 * 24;
if (diffDays > 30) {
datePrice= 20;
}
return datePrice;
}
function calculateTotal()
{
var titleFees = getDatePrice(date);
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Estimated Transfer Fees $"+titleFees;
}
today - date = some time in milliseconds, if you multiply that value you'll get an astronomic number. Instead, get the number of days:
// Utils
const el = (sel, parent = document) => parent.querySelector(sel);
// Purchase form calculator
const elDate = el(`#formPurchase [name="purchasedate"]`);
const elInfo = el(`#transferFeeInfo`);
const calcTransferFees = () => { // Don't pass any arguments
const diffMs = elDate.value ? new Date() - new Date(elDate.valueAsDate) : 0;
const diffDays = Math.floor(diffMs / 1000 / 60 / 60 / 24);
const isOlderThan30Days = diffDays > 30;
const transferFees = isOlderThan30Days ? 20 : 0;
elInfo.textContent = `Estimated Transfer Fees ${transferFees} $`;
};
elDate.addEventListener("input", calcTransferFees);
<form id="formPurchase" name="form">
<label>Purchase Date <input type="date" name="purchasedate" required /></label>
<div id="transferFeeInfo"></div>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With