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

时间:2012-04-07 00:37:23

标签: javascript

嗨这让我疯了。我不是开发人员。试图让这个工作。 用户使用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());
}

我知道这是完全错误的,因为我说我不是开发人员或程序员,我无法弄清楚如何将此信息输入此字段并让我的原始字段仍显示。

感谢您阅读本文!

2 个答案:

答案 0 :(得分:0)

使用value代替setAttribute

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

答案 1 :(得分:0)

哇哇哇哇。

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

// 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
}

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

顺便说一句,不要使用try / catch。