Home  >  Q&A  >  body text

I need help fixing my html and java script code

<p>I want to make a place where you can enter your next birthday and the page will turn into a window. Remind you that your birthday is in a few days. When I run the code, before I enter the birthday, the alert says NaN, which means is not a number. I want it to work after I type my birthday and after I click submit. This is the code I wrote:</p> <p>` </p> <pre class="brush:php;toolbar:false;"><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>`</pre> <p><br /></p>
P粉201448898P粉201448898445 days ago567

reply all(1)I'll reply

  • P粉523625080

    P粉5236250802023-08-02 11:47:11

    <!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>

    reply
    0
  • Cancelreply