显示javascript结果,该结果是输入标记内日期之间差异的结果

时间:2017-08-26 11:05:58

标签: javascript html

我是新手,学习编程语言, 在这里,我想问一下如何将javascript结果(日期)放入输入标签html。

结果似乎没有出现在输入标记内。

这是我写的函数:

function updatesum() {
    var d1= new Date(document.getElementById("d1").value;);
    var d2 = new Date(document.getElementById("d2").value;);
    var total = (d2.getDate() - d1.getDate()) / 30 +
d2.getMonth() - d1.getMonth() +
(12 * (d2.getFullYear() - d1.getFullYear()));
    // alert(total);
    document.getElementById("txtTotal").value = total;
    return false;
}

这是html表单:

<br>
<form name="input" action="#" method="get" onsubmit="return false;" >
Start date:<input  class= "d1" type="text" name="d1" value="" id="d1" />
End Date:<input  class="d2" type="text" name="d2" value="" id="d2" />
<br>
<br>
Total Month in fraction:<input type="text" name="total" value=" " 
id="txtTotal"/>
<input type="submit" value="Submit" onclick="updatesum()"/>
</form>

函数的结果应该是输入形式

https://jsfiddle.net/syafieqq/c8L68bjj/2/

更新正确答案

http://jsfiddle.net/syafieqq/69m3LkLv/4/

1 个答案:

答案 0 :(得分:1)

您的代码中有拼写错误:

&#13;
&#13;
<header> date format ex: 2010/11/23</header>
<br>
<form name="input" action="#" method="get" onsubmit="return false;" >
  Start date:<input  class= "d1" type="text" name="d1" value="" id="d1" />
  End Date:<input  class="d2" type="text" name="d2" value="" id="d2" />
  <br>
  <br>
  Total Month in fraction:<input type="text" name="total" value=" " id="txtTotal"/>
  <input type="submit" value="Submit" onclick="updatesum()"/>
</form>

<script>
  function updatesum() {
    var d1= new Date(document.getElementById("d1").value); // was value;); removed inner ;
    var d2 = new Date(document.getElementById("d2").value); // was value;); removed inner ;

    var total = (d2.getDate() - d1.getDate()) / 30 +
        d2.getMonth() - d1.getMonth() +
        (12 * (d2.getFullYear() - d1.getFullYear()));
    // alert(total);
    document.getElementById("txtTotal").value = total;
    return false;
  }
</script>
&#13;
&#13;
&#13;