skip to Main Content

I want to make a place where you key in your next birthday and the page does a window.alert to tell you how many days are left for your birthday. When I run the code, before I key in the birthday, the alert says NaN which means not a number. I want it to work after I key in the birthday after I click submit. This is what I coded:

`

<input type="submit" value="Submit">
    
</form>

<script>
let date_1 = new Date(document.getElementById("bday").value);
let date_2 = new Date();

let difference = date_1.getTime() - date_2.getTime();
let TotalDays = Math.ceil(difference / (1000 * 3600 * 24));
window.alert(TotalDays);

</script>
</body>`

2

Answers


  1. <!DOCTYPE html>
    <html>
    <head>
      <title>Birthday Countdown</title>
    </head>
    <body>
      <form onsubmit="calculateDaysLeft(event)">
        <label for="bday">Enter your birthday:</label>
        <input type="date" id="bday" name="bday" required>
        <input type="submit" value="Submit">
      </form>
    
      <script>
        function calculateDaysLeft(event) {
          event.preventDefault(); // Prevent form submission to avoid page reload
    
          // Get the user's birthday from the input field
          let userBirthday = new Date(document.getElementById("bday").value);
    
          // Get the current date
          let currentDate = new Date();
    
          // Calculate the difference in milliseconds
          let difference = userBirthday.getTime() - currentDate.getTime();
    
          // Calculate the difference in days and show the alert
          let totalDays = Math.ceil(difference / (1000 * 3600 * 24));
          window.alert(`There are ${totalDays} days left until your birthday!`);
        }
      </script>
    </body>
    </html>
    Login or Signup to reply.
  2. I see basically two problems here.
    First of all, the value that you are getting from bday is going to be a string, so you should be sure of the format of that value. You need to get the day, the month and the year, in order to create a string like "day/month/year", to convert it into a date type, using Date.parse().

    Secondly, to get the actual date, you should use Date.now(). The constructor alone will not work.

    Apllying these changes we have:

    let date_1 = Date.parse("13/10/2023");
    let date_2 = Date.now();
    
    let difference = date_1 - date_2;
    let TotalDays = Math.ceil(difference / (1000 * 3600 * 24));
    window.alert(TotalDays);
    

    Have a nice day!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search