JavaScript - 输入日期,然后自动填充下一个字段的差异

JavaScript - Input a date then autopopulate next field with difference

本文关键字:下一个 填充 字段 输入 日期 然后 JavaScript      更新时间:2023-09-26

嗨,这让我发疯了。我不是开发人员。试图让它工作。用户使用 Date 对象(日历)将日期(雇用日期)放入表单中下一个字段应采用该日期并减去今天的日期以获得工作时长。但是我在现场没有定义,我原来的雇用日期消失了。这是我所拥有的,请帮忙,非常感谢!

//grab date of hire
try{document.getElementById("dData_DOH").onchange =          custom_calculateDate;}catch(e){}
//not sure if necessary - field that the difference should go to
try{document.getElementById("dData_LengthEmp").onblur =     insertDate;}catch(e){}
//Function to grab input hire date 
//Create variable for now
//Create variable for difference

function custom_calculateDate(){
 var hireDate = document.getElementById("dData_DOH").value = "";
     var timeNow= new Date();
 var diff = Math.abs(timeNow - hireDate);
document.getElementById("dData_DOH").setAttribute('value',     custom_calculateDate());
     }
//Function to get the difference into the LengthEmp field    
function insertDate() {
document.getElementById("dData_LengthEmp").setAttribute("",     custom_calculateDate());
}

我知道这是完全错误的,正如我所说,我不是开发人员或程序员,我无法弄清楚如何将这些信息放入该领域并让我的原始字段仍然显示。

感谢您阅读本文!

使用 value 而不是 setAttribute

document.getElementById("dData_DOH").value = custom_calculateDate();

哇哇。

我将尝试通过解释原因来重写您的代码:

// Firstly, the onchange event doesn't work on IE for text inputs, prefer onblur
document.getElementById('dData_DOH').onblur = function(e) {
    // Now let's get some variables
    var hireDate = this.value, // "this" refers to the element that triggered the event
        now = new Date(),
        // You were on the right track for the difference, almost!
        diff = Math.abs(new Date(now.getTime() - hireDate.getTime()))
    // Finally, just don't change the original field, but the one you wanted to modify
    document.getElementById('dData_LengthEmp').value = diff.toTimeString() // Get the time as a readable format
}

我还没有测试过解决方案,但它应该让你走上正轨。

顺便说一句,不要使用尝试/捕获。