0

I'm very curious as to why my code won't run properly. I retrieve the value for the Date input from the html file and I created a function to find the difference; however, the span element will not update. Please explain to me why I'm wrong and what I could do to fix it. Thanks!

Code

const setup = () => {

  let firstDate = $('#firstDate').val();
  let secondDate = $('#secondDate').val();

  const findTheDifferenceBetweenTwoDates = (firstDate, secondDate) => {
    let timeDifference = Math.abs(secondDate.getTime() - 
    firstDate.getTime());

    let millisecondsInADay = (1000 * 3600 * 24);
    let differenceOfDays = Math.ceil(timeDifference / secondsInADay); 

    return differenceOfDays;
  }

 let result = findTheDifferenceBetweenTwoDates(firstDate, secondDate);

 $("span").text(result);

}

2 Answers2

0
 $("span").text(result); 

should be replaced with

$("#span").text(result);

if span is an id of the HTML element.

0

I found your problem its not from the span, the problem is from javascript you should parse the string date into js new Date also you have a typo in secondsInADay should be millisecondsInADay

also there is a bug that the code will run when doc is ready this is wrong because you are waiting input from user so I added a submit button

check this codepin: https://codepen.io/hassanalisalem/pen/gGLyvJ

your HTML

<div class="container">
  <h1>Date Difference!</h1>
  <h1>First Date</h1>
    <input id="firstDate" type ="date">
  <br/>
   <h1>Second Date</h1>
    <input id="secondDate" type ="date">
  <br>
  <h1>Amount of Days: <span id="result"></span></h1>
  <button id="submit">submit</button>
</div>

your js:

const animateBg = (i) => {
    document.body.style.backgroundColor = 'hsl(' + i + ', 100%, 50%)';

    setTimeout(function() {
        animateBg(++i)
    }, i);
}
animateBg(0);

const setup = () => {
  let firstDate = $('#firstDate').val();
  let secondDate = $('#secondDate').val();
  const findTheDifferenceBetweenTwoDates = (firstDate, secondDate) => {
  firstDate = new Date(firstDate);
    secondDate = new Date(secondDate);

    let timeDifference = Math.abs(secondDate.getTime() - firstDate.getTime());

    let millisecondsInADay = (1000 * 3600 * 24);

    let differenceOfDays = Math.ceil(timeDifference / millisecondsInADay);

    return differenceOfDays;

  }

  let result = findTheDifferenceBetweenTwoDates(firstDate, secondDate);
  alert(result);
  $("#result").text(result);


}

$(document).ready(function () {
  $('#submit').click(function () {
    setup();
  })
});

now it should work it worked on codepen

HSLM
  • 1,692
  • 10
  • 25
  • You can post runnable snippets here. – RobG Sep 25 '17 at 09:59
  • Even if I am using ES2015? I did add the working codepen at the beginning of the answer :) -> https://codepen.io/hassanalisalem/pen/gGLyvJ – HSLM Sep 25 '17 at 10:06