需求是這樣, 有開始日和結束日
之前day的邏輯是
日數 X 次數 = 總劑量
但是其實~一周中, 只有幾天是有效天數, 其他天數都無效
比方說1/3是星期一, 因此~計算次數1/3-1/10, 應該是星期一, 三, 五, 一
總共是4次, 這個在js和html怎麼做到呢?
doctorPrescriptionEditModal.find("input[name='doctor_prescription_week']").on("change", function () {
calculateDose();
});
對於點選checkbox進行綁定動作
這裡checkbox如下
function calculateDose(){
var eachDoseShow = doctorPrescriptionEditModal.find("#doctor_prescription_each_dose").val();
var eachDose = Number(eachDoseShow);
if(eachDoseShow==''){
eachDose = Number('0');
}
var weekDay = doctorPrescriptionEditModal.find("input[name='doctor_prescription_week']:checked").serialize()
.replace(/doctor_prescription_week=/g, "").replace(/&/g, "");
//此時資料若為星期一三五, 則weekDay為135
var weekArr = [],
var sNumber = weekDay.toString();
for (var i = 0, len = weekDay.length; i < len; i += 1) {
weekArr.push(+sNumber.charAt(i));
}
console.log("weekArr="+weekArr);
//這時 weekArr = [1,3,5]
var dayCount = getCountOf(strDate, endDate, weekArr);
console.log("dayCount="+dayCount);
//最後計算count天, 乘上一天幾劑, 就會成為總劑量
doctorPrescriptionEditModal.find("#doctor_prescription_dose").val(dayCount*eachDose);
}
function getCountOf( date1, date2, weekArr ){
var dateObj1 = parseDate(date1);
var dateObj2 = parseDate(date2);
var count = 0;
//判斷從開始到結束, 一天一天順過去計算, 如果getDay的數字 同陣列中 weekArr = [1,3,5] 則count+1
while ( dateObj1.getTime() <= dateObj2.getTime() ){
if (weekArr.includes(dateObj1.getDay()) )
{
count++
}
dateObj1.setDate(dateObj1.getDate() + 1);
}
return count;
}
function parseDate(input) {
var parts = input.split('/');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}
詳細可以參考連結, 原版getCountOf的第三個參數是給文字 ex "Sun" , "Mon"
我改的版本是直接餵數字給他判斷
(範例在倒數兩個參考)
參考:
https://stackoverflow.com/questions/8423217/jquery-checkbox-checked-state-changed-event
https://www.itranslater.com/qa/details/2582427940055155712
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
https://stackoverflow.com/questions/35694378/count-mondays-in-a-given-date-range
https://jsfiddle.net/gurvinder372/e43rs5n4/1/
沒有留言:
張貼留言